Linux下C语言问题 pipe问题(急)

hopepark hopepark 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
小弟最近才开始学Linux下的C语言变成,还是只菜鸟。请问我下面的代码有什么问题啊?
小弟想写一个在主函数先输入N个单词,然后主函数生成N个子进程。然后父函数通过pipe将单词传给子进程,是子进程输出单词,具体想这么输出:
./a.out aa bbb cccc d
然后输入上面命令后,电脑输出:
2345 : aa
2356 : bbb
2378 : cccc
2379 : d
但是下面的代码运行后却是这样输出的:
root@localhost usp_ch06]# gcc parentwritepipe.c
[root@localhost usp_ch06]# .a.out aaa bb vv
[3076] aaa
[3076] bb
[3076] vv
[root@localhost usp_ch06]# [3077] aaa
q
bash q command not found
[root@localhost usp_ch06]# .a.out aaa bb vv
[3079] aaa
[3079] bb
[3079] vv
[root@localhost usp_ch06]# [3080] aaa
q
bash q command not found
[root@localhost usp_ch06]#
请问这是哪里有问题啊,下面是代码,这个代码是我从书上一个例题改编的,问题应该很多,请大家指教
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#define BUFSIZE 10

int main(int argc,char *argv[])
{
int i=1;
int bytesin;
pid_t childpid;
int fd[2];
if (argc < 2)
{
fprintf(stderr,"Usage: %s command arg1 arg2 ...\n",argv[0]);
return 1;
}
if (pipe(fd) == -1)
{
perror("Failed to create the pipe");
return 1;
}
bytesin = strlen(argv[1]);
childpid = fork();
if (childpid == -1)
{
perror("Failed to fork");
return 1;
}
while(argv[i] != NULL)
{
if (childpid) /* parent code */
write(fd[1], argv[i], strlen(argv[i])+1);
else /* child code */
bytesin = read(fd[0], argv[i], BUFSIZE);
fprintf(stderr, "[%ld]: %.*s\n",
(long)getpid(), bytesin, argv[i]);
i=i++;
}
return 0;
}
...全文
评论 7
收藏 已收藏
分享
返回顶部
hopepark
C语言 70,040 成员 243,237 内容