Hi guys.
I've a problem with pipes, I'm trying to make a program that can create a child process and they must generate the folowing output:
Ping ... Pong
Ping ... Pong
Ping ... Pong
I want syncronize the output whithout using the semephores, can anyone help me?
Thanks in advance.
/**
* @file main.c
* @brief Description
* @date 01-01-2006
* @author
eiYxxxxx@student.estg.ipleiria.pt
*/
#define FFORK 1
#define FPIPE 2
#define FIO 3
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
void error_ (int code, char *message, ...){
fprintf(stderr,"%s \n", message);
exit(code);
}
int main(int argc, char *argv[])
{
/* Variable declaration */
int fd_p[2];
int fd_s[2];
int buf = 0;
int WRITE = 1;
int NO_WRITE = 0;
ssize_t io_bytes = 0;
static int j = 0;
/* Main Code*/
(void) argc, (void) argv;
;
if ((pipe(fd_s) != 0) || (pipe(fd_p) != 0))
error_(FPIPE,"Pipe Failed!\n");
setvbuf(stdout,(char*) NULL,_IONBF,0);
switch (fork()){
case -1:
error_(FFORK,"Failed Fork!\n");
break;
case 0 :
while (1){
if (j == 0){
if (close(fd_p[1]) != 0)
error_(FIO,"Failed Close!\n");
if (close(fd_s[0]) != 0)
error_(FIO,"Failed Close!\n");
}
if ((io_bytes = write(fd_s[1],&NO_WRITE, sizeof(int))) == -1)
error_(FIO,"Failed Write!\n");
if ((io_bytes = read (fd_p[0], &buf, sizeof(int))) == -1)
error_(FIO,"Failed Read");
if (buf == WRITE){
printf("Pong!\n");
if ((io_bytes = write(fd_s[1],&WRITE, sizeof(int))) == -1)
error_(FIO,"Failed Write!\n");
}
sleep(1);
j++;
}
break;
default:
while (1){
if (j==0){
if (close(fd_p[0]) != 0)
error_(FIO,"Failed Close!\n");
if (close(fd_s[1]) != 0)
error_(FIO,"Failed Close!\n");
}
if ((io_bytes = write(fd_p[1],&NO_WRITE,sizeof(int))) == -1)
error_(FIO,"Failed Write!\n");
/* Starting the Synchrinization */
if (j==0)
printf("Ping...");
if ((io_bytes = write(fd_p[1], &WRITE, sizeof(int))) == -1)
error_(FIO,"Write Failed!\n");
else
buf = NO_WRITE;
if ((io_bytes = read(fd_s[0], &buf, sizeof(int))) == -1)
error_(FIO,"Failed Read!\n");
if (buf==WRITE){
printf("Ping... ");
if ((io_bytes = write(fd_p[1],&WRITE,sizeof(int))) == -1)
error_(FIO,"Failed Write");
}
sleep(1);
j++;
}
}
return 0;
}