如何解决从管道读取后程序停留在后台
我正在做一个管道练习,基本上我必须编写一个程序来接收一个字符串并将其转换为一个 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 条件使进程保持运行,问题是我真的不知道如何停止它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。