【发布时间】:2016-11-11 05:44:22
【问题描述】:
[已解决] 所以对于这个练习练习,我被分配到练习过程控制。我只是想知道为什么我的子进程似乎永远不会执行(当 child_pid == 0 时)。对此问题的任何帮助将不胜感激! 另外,safe_fork() 是我们的讲师为了避免学生打开太多进程而编写的一个函数。
#include "safe-fork.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
int main(void) {
pid_t child_pid;
int pipefd[2];
int pipe_result;
int count;
pipe_result = pipe(pipefd);
if (pipe_result == -1) {
perror("pipe failure");
exit(1);
}
child_pid = safe_fork();
/*Parent Process*/
if (child_pid > 0) {
dup2(pipefd[0], STDIN_FILENO);
scanf("%d", &count);
if (count > 200) {
printf("Long enough!\n");
exit(0);
}
else {
printf("Too short!\n");
exit(1);
}
}
/* Child Process */
else {
dup2(pipefd[1], STDOUT_FILENO);
execl("/usr/bin/wc", "-w");
}
return 0;
}
【问题讨论】:
-
在调用任何
scanf()系列函数时,始终检查返回值(而不是参数值)以确保操作成功。当调用任何exec()系列函数时,它们只会在发生错误时返回,因此在调用之后使用:perror( "exec?? failed"); exit(1); -
父进程应该调用
waitpid( child_pid, NULL ); before returning. In the current scenario, the child will never return because no file/input is passed to thewc` 函数,这样它就会永远坐着,看着标准输入,进行输入。建议添加另一个参数,即要计算这些单词的文件名。注意:execl()的参数列表应以 NULL 参数结尾。注意:退出父进程会使子进程(如果它尚未退出,在这种情况下它还没有退出)进入zombie进程,需要重新启动才能消除。 -
调用
fork()时,返回值是三个,而不是两个,(即-1错误)代码需要正确处理-1返回值。 -
对
execl()函数的调用具有以下语法:int execl(const char *path, const char *arg, ... /* (char *) NULL */);所以这一行:execl("/usr/bin/wc", "-w");应该更像:execl("/usr/bin/wc", "-w", file.txt, (char *) NULL ); -
建议每个 4 级空格缩进,因为即使是可变宽度字体也可以看到
标签: c multithreading unix multitasking