c - fork() 返回正数而不是零

标签 c process fork

当我在代码中只使用一次 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。 child 得零分。

不会打印“got to child”行,因为 printf 会缓冲输出,直到打印换行符为止,并且在 stdout 句柄有机会刷新缓冲区之前关闭它。在其末尾插入 \n,或删除 close(STDOUT_FILENO) 行。

关于c - fork() 返回正数而不是零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56079830/

相关文章:

c - 标记多个字符串 C

c - 使用文件执行复制命令我的代码正在复制垃圾?

linux - Unix 域套接字辅助数据

project-management - 您的 Web 开发过程由哪些步骤组成,每个阶段需要多长时间?

c - 如何将stdin通过管道传递给 child 并在C中执行猫

c - Misra C 规则 12.2 - 误报警告?

c++ - 将无符号字符按位左移 16 是什么意思

linux - fork() 如何知道它是在子进程中还是在父进程中?

c++ - 在 C 中,当管道输入到另一个程序时,它无法打开

ruby - 在 Windows 上的 Ruby 中生成后台进程?