- 7.1
输出:
4:ABCD
4:EFGH
- 7.2
输出:
numbers=3
10
20
30
- 7.3
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdint.h>
#include <string.h>
#define BUFSIZ 1024
struct grade
{
char sno[20];
char name[10];
float chinese,math,english;
};
int main()
{
int fds[2];
if (pipe(fds) < 0)
{
fprintf(STDERR_FILENO,"pipe failure \n");
exit(EXIT_FAILURE);
}
int pid = fork();
if (pid == 0)
{
close(fds[0]);
write(fds[1],"1234567890",11);
struct grade gra = {"001","nihao",60,60,60};
write(fds[1],&gra,sizeof(struct grade));
close(fds[1]);
}
else
{
close(fds[1]);
uint8_t buff[BUFSIZ];
read(fds[0],buff,sizeof(buff));
printf("read num: %s \n",buff);
struct grade *gra = buff+strlen(buff)+1;
printf("read grade{name:%s, sno:%s, chi:%.2f, math:%.2f, eng:%.2f} \n"
,gra->name,gra->sno,gra->chinese,gra->math,gra->english);
close(fds[0]);
}
exit(EXIT_SUCCESS);
}
- 7.4
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("\n");
int pipe_ids[2];
pipe(pipe_ids);
int pid0 = fork();
if (pid0 == 0)
{
close(pipe_ids[0]);
int save_stdout = dup(1); // save stdout
close(1); // close stdout
dup(pipe_ids[1]); // stdout -> pipe_ids[1]
execlp("ps","ps","-aux",NULL);
dup2(save_stdout,1); // restore stdout
close(pipe_ids[1]);
exit(EXIT_SUCCESS);
}
int pid1 = fork();
if (pid1 == 0)
{
close(pipe_ids[1]);
int save_stdin = dup(0); // save stdin
close(0); // close stdin
dup(pipe_ids[0]); // stdin -> pipe_ids[0]
execlp("grep","grep","init",NULL);
dup2(save_stdin,0); // restore stdin
close(pipe_ids[0]);
exit(EXIT_SUCCESS);
}
close(pipe_ids[0]);
close(pipe_ids[1]);
return 0;
}
to be continue …