如何正确使用fork()和exec()

我有这个代码;

pid_t process; process = fork(); if (process < 0){ //fork error perror("fork"); exit(EXIT_FAILURE); } if (process == 0){ //i try here the execl execl ("process.c", "process" , n, NULL); } else { wait(NULL); } 

我不知道fork()exec()是否正确。 当我尝试从bash运行程序时,我没有收到任何结果,所以我认为这部分代码可能存在问题。
谢谢。

一个问题是

 if (process = 0){ 

应该读

 if (process == 0){ 

否则,您将为process 分配零,并且仅在result为非零(即从不)时仅调用execl

此外,你正在尝试执行一个名为process.c东西。 毫无疑问,可以有一个名为process.c的可执行文件。 但是,传统上以.c结尾的名称将被赋予C源代码文件。 如果process.c确实是一个C文件,则需要先编译并链接它。

一旦构建了可执行文件,就需要将它放在$PATH上的某个位置,或者指定execle()完整路径。 在许多Unix环境中,将它放在当前目录中是不够的。

最后,不清楚execle()调用中的n是什么,但名称提示数字变量。 你需要确保它是一个字符串,而不是一个整数。

那么根据上面的答案和评论你的代码应该看起来像这样

 pid_t process; process = vfork(); //if your sole aim lies in creating a child that will ultimately call exec family functions then its advisable to use vfork if (process < 0) { //fork error perror("fork"); exit(EXIT_FAILURE); } if (process == 0) { //i try here the execl char N[MAX_DIGITS];//A correction here itoa(n,N);//write this function yourself execl ("process", "process" , N, NULL);// Here process is the name of the executable N is your original argument fprintf(stderr,"execl failed\n");//check for error in execl } else { wait(NULL); } 

注意使用vfork而不是fork.Its因为它会更有效。原因可以在这里找到