所以,我想做的是创建一个子进程,让它执行 execl 并运行 ls。然后在 ls 完成后,创建另一个子进程并让它在文件上运行 cat 命令。第二个 wait(pid) 似乎没有等待第二个子进程完成才完成。这是我的代码和输出
#include <fcntl.h>
int main(){
int pid;
printf("In parent process, creating child now...\n");
pid = fork();
if (pid==0){
printf("Now in child process...\n");
execl("/bin/ls","ls","-l",(char*)0);
}
wait(pid);
printf("ls child process complete\n");
printf("in parent process\n");
printf("Creating another child process\n");
pid=fork();
if(pid==0){
execl("/bin/cat","cat","f1",(char*)0);
}
wait(pid);
return 0;
}
这是我的输出
In parent process, creating child now...
Now in child process...
"Contents of ls"
ls child process complete
in parent process
creating another child process
[username@host ~]$ "Contents of file" *cursor*
父进程似乎在第二个子进程完成之前就结束了。一次只有 1 个 child 。 “文件内容”应该出现在 [username@host ~]$ 提示符之前。我想我放错了等待或错误的 pid 分配或其他东西。提前致谢!
最佳答案
wait()
的参数不是 PID。它是指向将存储退出状态的 int
的指针。您在需要指针的地方传递了一个整数,这意味着:
- 一旦您调用
wait
,程序可能会崩溃或损坏一些不相关的内存位置。它在那之后的行为是不可预测的。 - 您需要启用更多的编译器警告并注意它们。
关于c - 为什么我的父进程没有等待第二次? C/Unix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26898640/