69,373
社区成员
发帖
与我相关
我的任务
分享
#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;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#define MAX_PROC 10
#define BUFSIZE 10
#define E_EXIT(msg) do{fprintf(stderr, msg); return 1;}while(0)
int main(int argc,char *argv[])
{
if (argc-- < 2)
E_EXIT("Usage: command arg1 arg2 ...\n");
pid_t childpid[MAX_PROC];
int w, i, fd[MAX_PROC][2];
char buf[BUFSIZE];
for (i=0; i<argc; i++)
if (pipe(fd[i]) == -1)
E_EXIT("Failed to create the pipe");
for (i=0; i<argc; i++) {
childpid[i] = fork();
if (childpid[i] == -1)
E_EXIT("Failed to fork");
if (childpid[i]>0)
close(fd[i][0]);
else {
close(fd[i][1]);
read(fd[i][0], buf, BUFSIZE);
printf("%d : %s\n", getpid(), buf);
exit(0);
}
}
for (i=0; i<argc; i++)
write(fd[i][1], argv[i+1], strlen(argv[i+1])+1);
for (i=0; i<argc; i++)
wait(&w);
return 0;
}