首页 > 解决方案 > 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);
    }

标签: cprocessfork

解决方案


到时间fork()返回时,您有两个(几乎)相同的进程正在运行 - 父进程和子进程。就好像你运行了你的程序两次。

父进程从 fork() 获得正返回 - 子进程的 PID。孩子得了零分。

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


推荐阅读