c - fork() 返回正数而不是零
问题描述
我在理解为什么当我在代码中只使用一次 fork() 时返回正数而不是零时遇到问题。我一直在寻找解决方案几个小时,但没有任何帮助。这是代码
#include <stdio.h>
#include <stdlib.h> //for exit
#include <fcntl.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h> //for sleep(),execvp()
#include <ctype.h>
#include <fcntl.h>
#define IN 0
#define OUT 1
#define SIZE 9
int main(int argc, char * argv[]) {
int pipe_descs[2];
int matrix[SIZE][SIZE];
int fdr, fdw; // file descriptors
int i;
int status=0;
/*if (pipe(pipe_descs) == -1) {
fprintf(stderr, "cannot open");
exit(1);
}*/
fdr = open(argv[1], O_RDONLY); // open files
fdw = open("gg.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
if (fdr < 0 || fdw < 0) { //validation for error
perror("failed to open input or output files");
exit(EXIT_FAILURE);
}
removeSpaces(matrix, fdr, fdw);
status=fork();
if (status < 0) {
fputs("error in fork", stderr);
exit(EXIT_FAILURE);
}
if(status == 0) {
printf("got to child");
dup2(pipe_descs[IN],0);
close(pipe_descs[IN]);
dup2(pipe_descs[OUT],4);
close(STDOUT_FILENO);
}
close(fdr); // close the files
close(fdw);
exit(EXIT_SUCCESS);
}
解决方案
到时间fork()
返回时,您有两个(几乎)相同的进程正在运行 - 父进程和子进程。就好像你运行了你的程序两次。
父进程从 fork() 获得正返回 - 子进程的 PID。孩子得了零分。
没有打印“got to child”行,因为printf
在打印换行符之前缓冲输出,并且在它有机会刷新缓冲区之前关闭 stdout 句柄。\n
在其末尾插入 a或删除该close(STDOUT_FILENO)
行。
推荐阅读
- jquery - 如何在使用 jQuery 更新表单字段值时排除“隐藏”类型字段
- types - 为什么以下类型声明和/或实例化在 Julia 1.0 中不起作用?
- r - 使用 filter_if 根据条件进行过滤
- html - 在社交媒体帖子中正确显示网站?
- node.js - 如何在 Node.js 中使用 selenium-webdriver 连接到 CEFSharp 应用程序
- c# - 去除除某些 HTML 标签之外的所有 HTML 标签?
- reactjs - React TypeScript,不能使用上下文来改变画布
- angular - 为什么我们需要在 angular prod build 中设置“--aot false”?
- javascript - 如何根据索引号为选择选项设置值?
- java - 出现错误,org.postgresql.util.PSQLException: ERROR: syntax error at or near "." ,当尝试将列表传递给休眠中的新类时