首页 > 解决方案 > 从管道读取后程序停留在后台

问题描述

我正在使用管道进行练习,基本上我必须编写一个接收字符串并将其转换为 int 的程序(我不允许编辑执行代码)并且我不明白为什么从我的程序生成的过程没有停止。

这是练习:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define PIPEOUT "/tmp/pipeOut"
#define MAXNUM 1024
#define MAXBUF 1024
#define CHALLENGES 3

int main() {
    int fd_in, fd_out, i;
    int challenge;
    char buffer[MAXBUF];

    unlink(PIPEOUT);

    if (mkfifo(PIPEOUT,0666)<0) {
        perror("Error while creating pipe");
        exit(EXIT_FAILURE);
    }
    fd_out = open(PIPEOUT, O_WRONLY);

    if (fd_out<0) {
        perror("Error while opening pipe");
        exit(EXIT_FAILURE);
    }

    srandom(time(NULL));

    for(i=0;i<CHALLENGES;i++) {
        challenge = random()%MAXNUM;
        if (snprintf(buffer,MAXBUF,"%d\n",challenge)>=MAXBUF) {
            printf("Buffer error!\n");
            exit(EXIT_FAILURE);
        }
        printf("Invio %s",buffer);
        if(write(fd_out,buffer,strlen(buffer))<0) {
            perror("error during write");
        }
    }
    return 0;
}

这是我必须与练习一起使用的代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define PIPEOUT "/tmp/pipeOut"
#define MAXNUM 1024
#define MAXBUF 1024
#define CHALLENGES 3

void main(){
    int fd0,fd1;    // pipe descriptors
    char c;         // read char
    char str[1024]; // buffer
    int index = 0;  // index of buffer
    int num = 0;
    memset(str,'\0',1024); // init string

    fd0 = open(PIPEOUT,O_RDONLY);

    if (fd0<0) {
        perror("Error with pipe");
        exit(EXIT_FAILURE);
    }
    while(read(fd0,&c,1)) {
        if(c != '\n') {
            printf("received: %c\n", c);
            str[index++] = c;
        } else {
            num = atoi(str);
            printf("print number: %d\n", num);
            index = 0;
        }
    }
    close(fd0);
}

要执行练习,我使用以下命令:

(sleep 1; ./solution) & ./exercise

如果我做:

ps

它表明程序仍在运行但什么也不做(如果我没记错,这应该称为“僵尸进程”,因为它永远不会被终止),问题是练习发送的字符串不以 '\0 结尾' 我们必须想办法让进程结束,所以几乎可以肯定是 while 条件让进程保持运行,问题是我真的不知道如何停止它。

标签: cprocessiopipe

解决方案


推荐阅读