在我的c程序(在linux上运行)中,以下代码中的wait()
函数不会挂起父进程,因此可以先运行子进程。
//some code here...
char *glib_compile = "glib-compile-resources";
char *source_dir = unlimited_strcat("--sourcedir=", work_dir, NULL);
pid_t child_pid = fork();
if (child_pid == -1) {
perror("Error forking process");
exit(EXIT_FAILURE);
} else if (!child_pid) {
printf("%s\n", "child");
execlp(glib_compile, glib_compile, source_dir, gresource_xml_file,
NULL);
perror("Error compiling gresource");
_exit(127);
}
if (wait(NULL) == -1) {
perror("Error waiting for child process");
exit(EXIT_FAILURE);
}
printf("%s\n", parent);
free(gresource_xml_file);
free(source_dir);
//some code here...
如您所见,我放置了两个printf()
函数来查看首先运行哪个进程,并且在运行程序时,我会在parent
之前显示child
输出。
$ ./myprogram
parent
child
我用另一个非常简单的程序测试了wait()
,并且等待功能按预期工作,但是在我的特定程序中,它不起作用。我还设法通过使用child
函数使程序在parent
之前显示waitpid(child_pid, NULL, 0)
进程。
所以我的问题是,为什么当我使用wait()
来等待任何子进程执行时,代码将忽略wait命令而不暂停父进程,并且当我将我的子进程ID专门传递给[ C0]我的程序功能正常吗?
我已经阅读了手册页和许多网页,但是对于这种奇怪的行为我一无所知。
因为您没有在调用 childwaitpid()
或调用wait()
时加上“ if / else if”,所以子进程和父进程将调用它们。当孩子试图将其没有的孩子踩到printf("%s\n", parent);
时,它会立即返回并调用wait()
长话短说,这是