【问题标题】:Execute code after exec* function family在 exec* 函数族之后执行代码
【发布时间】:2016-07-07 00:10:45
【问题描述】:

我是 C 系统编程的新手。 我想在 exec* 函数族之后执行代码,但我不知道具体如何。

我读到我需要 fork,然后尝试在 exec* 函数之后执行代码。我确实分叉了我的进程,但是 exec* 函数之后的代码仍然不起作用。

到目前为止,这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc,char *argv[]){

printf("Programme de manipulation de recouvrement en C\n\n");
int status,infoStats;
pid_t processusFils;

//Usage du programme 
if(argc == 1){
    printf("USAGE : %s args1 ... argN \n\n",argv[0]);
    exit(1);
}

processusFils = fork();
if(processusFils < 0){
    perror("Erreur fork du processus fils ");
    exit(1);
}
if(processusFils == 0){

    execvp(argv[1],argv+1);

    exit(0);

}

printf("Hello world \n");
return 0;
}

有什么想法吗? 谢谢你

【问题讨论】:

  • 我假设您的意思是 printf 不起作用,因为 exit(0); 有点毫无意义。无论如何,您在此处发布的内容对我有用。
  • @WhozCraig,是的,这就是我的意思;调用 exec 函数后 printf 语句不起作用。
  • 你知道我怎样才能让它工作吗?
  • 这里看起来不错:ideone.com/TCkYbu
  • @OliverCharlesworth :这是行不通的,除非我们使用 wait(NULL)

标签: c unix operating-system


【解决方案1】:

经过多次编辑,如果有人需要,这里是正确的答案。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc,char *argv[]){

printf("Programme de manipulation de recouvrement en C\n\n");
int nombre1,nombre2;
pid_t processusFils;

//Usage du programme 
if(argc == 1){
    printf("USAGE : %s args1 ... argN \n\n",argv[0]);
    exit(1);
}


processusFils = fork();
wait(NULL);
if(processusFils < 0){
    perror("Erreur fork du processus fils ");
    exit(1);
}
if(processusFils == 0){
    execvp(argv[1],argv+1);
    exit(0);

}
printf("Hello world \n");

return 0;
}

我们只需要添加一个wait(NULL),这样我们就可以等待“子进程”的终止。之后,将由父级继续执行代码。

祝你好运

哈贾尔

【讨论】:

  • 如果您费心检查wait() 的返回值,您会注意到在孩子中wait() 不是一个好主意。
  • @EOF :这就是我要找的。等待子进程完成,然后“父进程”将继续执行代码。这就是我在我的例子中寻找的东西,我不是在笼统地谈论,也不是给出一个通用的解决方案。
  • 不,你也是wait()ing in in the child。由于子级没有自己的子级,因此子级中的 wait() 返回错误,您将忽略该错误。这不是好的设计。
  • @EOF:啊,好吧,现在我明白了 :) 那么你有什么好的设计建议呢?
  • wait() 移动到printf("Hello World \n"); 的正上方,只有父级会执行它。此外,您可能需要检查wait() 是否返回错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多