r305_dm/TP5/Exo2/pipe-ex.c

70 lines
1.0 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
int main(int argc, char *argv[])
{
pid_t p;
int fd[2];
char c;
if (pipe(fd) == -1)
{
exit(1);
}
p = fork();
assert(p != -1);
int id = 0;
if (p == 0)
{
id += 2;
}
p = fork();
assert(p != -1);
if (p == 0)
{
id += 1;
}
if (id == 0)
{
wait(NULL);
wait(NULL);
}
if (id == 2)
{
wait(NULL);
}
while (id == 1)
{
int w = write(fd[1], &p, sizeof(pid_t));
assert(w == sizeof(pid_t));
printf("%d sent %d\n", p, p);
sleep(3);
}
while (id == 3)
{
int op;
int r = read(fd[0], &op, sizeof(pid_t));
assert(r == sizeof(pid_t));
printf("\t%d received %d\n", p, op);
sleep(1);
}
}