为什么子进程不会在此代码中执行?

问题描述 投票:-1回答:1

子进程被跳过,idk为什么...我使用调试器,但是它没有给出任何线索为什么...仅通过以父进程的printf结尾的代码运行...在此先感谢。我第一次问一个问题时不知道该说些什么,它是在问我详细信息...但是我不知道还有什么要说的,代码的目的是运行“验证程序”程序,该程序是该程序可以在给定的字符串中验证存在多少个禁止的单词,因此我尝试了这一点,在这种情况下,我的“服务器”将通过管道与“ verificador”进行通信,然后保存要提供给“客户端”的禁止的单词数量。

#include <sys/errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

void myabort(const char * msg, int exit_status){
    perror(msg);
    exit(exit_status);
}

int main(int argc,char *argv[])
{
    pid_t pid;
    int fd[2],newfd,nbytes;
    int status;
    char word[]="filipe";
    FILE* f;

    if(pipe(fd)<0) myabort("unable to create unamed pipe",-1);

    switch(pid=fork()){
        case -1: // Error
                myabort("Unable to fork()",-3);
                break;

        case  0:

            printf("CHILD PROCESS");
            if(close(fd[0])==-1) myabort ("CHILD: Error while closing the read end of the pipe.",-4);
            if(close(STDOUT_FILENO)==-1) myabort ("CHILD: Error while closing the standard output.",-4);
            if(dup(fd[1])==-1) myabort("CHILD: Error while duplicating the pipe write end",-5);
            if(close(fd[1])==-1) myabort ("CHILD: Error while closing the original write end descriptor of the pipe.",-4);
            //fprintf(stdout, "%s", word);
            write(1,word,sizeof(word));
            break;

        default:/
            printf("PARENT PROCESS");
            wait(&status);
            close(STDIN_FILENO);
            newfd = dup(fd[0]);
            close(fd[0]);
            close(fd[1]);

            f = fdopen(newfd, "r");
            if(f == NULL) myabort("Error opening new file descriptor.", -1);

            execl("verificador", "verificador", "palavras_proibidas", NULL);

            break;
    }
}

c fork
1个回答
0
投票

它确实运行。这是缓冲流的问题。他们可能需要冲洗。

一种解决方案是添加换行符:

printf("CHILD PROCESS\n");

添加换行符在大多数情况下都可以使用,因为许多终端在遇到换行符时都会自动刷新。但您也可以更具体:

printf("CHILD PROCESS");
fflush(stdout);
© www.soinside.com 2019 - 2024. All rights reserved.