Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

One-way communication from a UNIX process to another through a pipe. Here\'s wha

ID: 3805027 • Letter: O

Question

One-way communication from a UNIX process to another through a pipe.

Here's what i got so far for communicate.c


#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

int
main(int argc, char *argv[])
{
int pfd[2];
pid_t cpid,rpid;
char buf;
int read_fd;
int write_fd;

if (pipe(pfd) == -1) { perror("pipe"); exit(EXIT_FAILURE); }


pfd[1] = fork();
if (pfd[1] == -1) { perror("fork"); exit(EXIT_FAILURE); }


if (pfd[1] == 0) {
pfd[1]= open("writer.c",O_WRONLY);
dup2(pfd[1],1);
close(pfd[1]);
close(1);
execlp("writer.c", "writer.c", NULL);
}

pfd[0] = fork();
if (pfd[0] == -1) { perror("fork"); exit(EXIT_FAILURE); }
if(pfd[0] == 0) {
pfd[0] = open("reader.c",O_RDONLY);
dup2(pfd[0],0);
close(pfd[0]);
close(0);
execlp("reader.c", "reader.c", NULL);
}
close(pfd[0]);
close(pfd[1]);
wait(0);
wait(0);
return 0;
}

It compiles with no errors but then when i use the UNIX command, communicate 5 (where 5 is n) it gives this:

./writer.c: line 1: /bin: Is a directory
./writer.c: line 6: syntax error near unexpected token `('
./writer.c: line 6: `int main(int argc, char *argv[])'
./reader.c: line 1: /bin: Is a directory
./reader.c: line 6: syntax error near unexpected token `('
./reader.c: line 6: `int main(int argc, char *argv[])'

The code for reader.c and writer.c is as follows:

/writer.c

#include
#include

int main(int argc, char *argv[])
{
int count; /* number of repetitions */
int i; /* loop control variable */

if (argc != 2)
{
printf("usage: writer count ");
return -1;
}
else count = atoi(argv[1]);

for (i = 0; i < count; i++)
{
printf("Hello");
printf("hello");
}
return 0;
}

//reader.c

#include
#define LINELENGTH 50

int main(int argc, char *argv[])
{
int count; /* number of characters in the line */
int c; /* input read */

count = 0;
while ((c = getchar())!= EOF)
{
putchar(c); count++;
if (count == LINELENGTH)
{
putchar(' '); count = 0;
}
}
if (count > 0)
putchar(' ');
return 0;
}

THANKS!

Explanation / Answer

Interprocess Communication using Pipes

WRITER.C

#include <fcntl.h>

#include<sys/stat.h>

#include<sys/types.h>

#include<unistd.h>

int main()

{

int f;

char *myfile = "/temp/myfile";

mkfifo(myfile, 0666);

f = open(myfile, O_WRONLY);

write(f, " HI", size of("HI"));

close(f);

unlink(myfile);

return 0;

}

READER.C

#include <fcntl.h>

#include<sys/stat.h>

#include<sys/types.h>

#include<unistd.h>

#define MAX 1024

int main()

{

int f;

char *myfile="/temp/myfile";

char buf[MAX];

f = open(myfile, O_RDONLY);

read(f, but, MAX);

printf("Received : %s ", but);

close(f);

return 0;

}