c - 从管道读取后程序停留在后台
问题描述
我正在使用管道进行练习,基本上我必须编写一个接收字符串并将其转换为 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 条件让进程保持运行,问题是我真的不知道如何停止它。
解决方案
推荐阅读
- python - 如何将剪贴画放在 matplotlib 中绘制的数据后面
- list - 使用通配符查找元组列表中元素的索引
- python - 使用来自输入的查询进行过滤
- python - Str object is not callable TypeError for Connect 4 game using Python
- ffmpeg - FFMPEG 用 BGR 转换而不是 RGB 分成两帧 | 开放式维诺
- apache-kafka - Kafka Log Compaction 总是显示相同键的最后两条记录
- swift - 如何快速排列collectionView单元格,就像一堆卡片一样
- html - 网页抓取标题属性的内容
- omnet++ - 使用 TraCIcommandInterface 在 Veins 中添加函数
- linux - 我正在尝试安装 docker。每当我运行 sudo apt-get update 时,我都会收到此错误: