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

小弟最近才开始学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;
}
1楼的朋友,实在不好意思,我的分都用光了,没有了,真是很对不起

你没给分啊

#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 pfd[2];
if (argc < 2) {
fprintf(stderr, "Usage: %s command arg1 arg2 ...\n", argv[0]);
return 1;
}
if (pipe(pfd) == -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) {
if (write(pfd[1], argv[i], strlen(argv[i])) != -1)
printf("parent write over.\n");
}else {
bytesin = read(pfd[0], argv[i], BUFSIZE);
fprintf(stderr, "[%ld]: %.*s\n", (long) getpid(), bytesin, argv[i]);
}
++i; ############关键是这里
}
return 0;
}
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网