Sending messages using pipe - C - c

I want to make NO_PROC processes, such that every process reads messages from its parent, and then writes those messages and one more message to its child, except in the case of the last process which writes its messages to stdout. So the i'th process will receive i-1 messages and will send to child i messages. I must use pipe to communication between processes. I wrote code but something is wrong and I can't find any bug :/. When NO_PROC = 5 I want the output to look like 4 lines with "my message", but in output I have one line: "my message" and 3 empty lines, like 3 messages are empty string :/. Note, err.h is my library which gives me function syserr() when something went wrong.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "err.h"
#define NO_PROC 5
#define BUF_SIZE 20
char message[] = "my message";
int parent;
char buf[BUF_SIZE];
int main()
{
for (int i = 0; i < NO_PROC; ++i) {
int pipe_dsc[2], buf_len;
if (pipe(pipe_dsc) == -1)
syserr("Error in pipe\n");
pid_t pid = fork();
if (pid == -1)
syserr("Error in fork\n");
else if (pid == 0)
parent = pipe_dsc[0];
else {
for (int j = 0; j < i; ++j) {
if ((buf_len = read(parent, buf, BUF_SIZE - 1)) == -1)
syserr("Error in read\n");
buf[buf_len < BUF_SIZE - 1 ? buf_len : BUF_SIZE - 1] = '\0';
if (i == NO_PROC - 1)
printf("%s\n", buf);
else if (write(pipe_dsc[1], buf, sizeof(buf)) != sizeof(buf))
syserr("Error in write\n");
}
if (i < NO_PROC - 1 && write(pipe_dsc[1], message, sizeof(message)) != sizeof(message))
syserr("Error in write\n");
if (wait(0) == -1)
syserr("Error in wait\n");
return 0;
}
}
}

I think your over complicating it and/or using the wrong approach. You don't have to send i messages to the ith process. Since the ith process is a copy (fork) of the i-1th process it has already received i-1 messages, and just needs one more. It's a rather symmetrical (and academic) problem.
Here is an example (robust error checking omitted). Note this relies on atomic pipe writes, which is fine as long as you not writing message greater that PIPE_BUF (see man pipe):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
void syserr(char * msg) { printf("%s\n", msg); exit(1); }
#define NO_PROC 5
#define BUF_SIZE 100
char message[] = "my message ";
int main() {
int message_len = 0;
char buf[BUF_SIZE];
for (int i = 0; i < NO_PROC; ++i) {
int pipe_dsc[2], buf_len;
if (pipe(pipe_dsc) == -1) {
syserr("Error in pipe\n");
}
pid_t pid = fork();
if (pid == -1) {
syserr("Error in fork\n");
}
else if (pid == 0) {
close(pipe_dsc[1]);
int n = read(pipe_dsc[0], buf+message_len, sizeof(buf));
message_len = strlen(buf); // Assume message is null terminated string.
if(i == NO_PROC -1) {
printf("Process %i: received '%s'\n", i+1, buf);
}
}
else {
close(pipe_dsc[0]);
write(pipe_dsc[1], message, sizeof(message));
wait(0);
return 0;
}
}
}

Related

C program hangs after fork

I have made the following program :
The aim is to make 5 child processes and have parent process send a string to each child process
to print. If I pass the argument xyz then this program prints xyz 2 times and then hangs.
Not sure why that is happening.
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int num_processes = 5;
int pipefd[num_processes][2];
pid_t cpid;
char buf;
if (argc != 2)
{
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
exit(EXIT_FAILURE);
}
for (int i = 0; i < num_processes; i++)
{
if (pipe(pipefd[i]) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < num_processes; i++)
{
cpid = fork();
if (cpid == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0)
{ /* Child reads from pipe */
close(pipefd[i][1]); /* Close unused write end */
while (read(pipefd[i][0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[i][0]);
}
else
{ /* Parent writes argv[1] to pipe */
close(pipefd[i][0]); /* Close unused read end */
write(pipefd[i][1], argv[1], strlen(argv[1]));
close(pipefd[i][1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
}
}
_exit(EXIT_SUCCESS);
}

Read and write using pipes

I have a program with 2 child processes which has to do the following:
use the parent to read data from a file 'data.txt' and write in a pipe
use a child to read the data from the pipe and filter the lowercase letters
use another child to write the filtered letters in a new file, each on a new line
I tried to do it and it works... kinda. The problem is, it writes the filtered letters in the desired file, but the program does not stop. What am I doing wrong?
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <string.h>
int parentChildpipeFileDescriptors[2], child1Child2FileDescriptors[2];
void parentProcess()
{
close(child1Child2FileDescriptors[0]);
close(child1Child2FileDescriptors[1]);
close(parentChildpipeFileDescriptors[0]);
int fileDescriptor = open("data.txt", O_RDONLY);
char buffer[8];
int store;
while ((store = read(fileDescriptor, buffer, 8)))
{
write(parentChildpipeFileDescriptors[1], buffer, store);
}
close(fileDescriptor);
close(parentChildpipeFileDescriptors[1]);
}
void child1Process()
{
close(parentChildpipeFileDescriptors[1]);
close(child1Child2FileDescriptors[0]);
char buffer[8];
int store, count = 0;
while ((store = read(parentChildpipeFileDescriptors[0], buffer, 8)))
{
for (int i = 0; i < store; i++)
{
if (buffer[i] >= 'a' && buffer[i] <= 'z')
{
count++;
write(child1Child2FileDescriptors[1], &buffer[i], sizeof(buffer[i]));
}
}
}
printf("CHILD 1 FINISHED FILTERING\n");
close(parentChildpipeFileDescriptors[0]);
close(child1Child2FileDescriptors[1]);
exit(count);
}
void child2Process()
{
close(parentChildpipeFileDescriptors[0]);
close(child1Child2FileDescriptors[1]);
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
char *fileName = "stat.txt";
int newFileDescriptor = creat(fileName, mode);
char buffer;
int store;
while ((store = read(child1Child2FileDescriptors[0], &buffer, 1)))
{
write(newFileDescriptor, &buffer, sizeof(buffer));
write(newFileDescriptor, "\n", 1);
}
close(newFileDescriptor);
printf("CHILD 2 FINISHED WRITING'\n");
close(child1Child2FileDescriptors[0]);
close(parentChildpipeFileDescriptors[1]);
exit(444);
}
int main(int argc, char const *argv[])
{
if (pipe(parentChildpipeFileDescriptors) < 0)
{
printf("ERROR CREATING PIPE\n");
exit(-100);
}
if (pipe(child1Child2FileDescriptors) < 0)
{
printf("ERROR CREATING PIPE\n");
exit(-101);
}
pid_t child1PID = fork();
if (child1PID < 0)
{
printf("ERROR CREATING CHILD\n");
exit(-200);
}
if (!child1PID)
{
child1Process();
}
pid_t child2PID = fork();
if (child2PID < 0)
{
printf("ERROR CREATING CHILD\n");
exit(-201);
}
if (!child2PID)
{
child2Process();
}
parentProcess();
int status1, status2;
waitpid(child1PID, &status1, 0);
waitpid(child2PID, &status2, 0);
printf("CHILD 1 TERMINATED WITH EXIT STATUS: %d\n", WEXITSTATUS(status1));
printf("CHILD 2 TERMINATED WITH EXIT STATUS: %d\n", WEXITSTATUS(status2));
return 0;
}
The read loop in child1process will never terminate, because child2 still has the write side of that pipe open. You need to execute:
close(parentChildpipeFileDescriptors[1]);
before you enter the read loop. The general rule is that if a process isn't going to use a file descriptor, it should close it immediately.
your while ((store = read(parentChildpipeFileDescriptors[0], buffer, 8))) loop is never gonna end.
The parent needs to say to the child that there is no more data coming and it shall not do another read.
You can do this by sending a special byte.
Example :
in the parent:
char endByte = 0x1;
write(parentChildpipeFileDescriptors[1], &endByte, 1);
//then close
in the while loop of the child :
if(buffer[i] == 0x1){
printf("CHILD 1 FINISHED FILTERING\n");
fflush(stdout);
close(parentChildpipeFileDescriptors[0]);
close(child1Child2FileDescriptors[1]);
exit(count);
};

Unable to process the pipe function

Unable to process the pipe function where a give pipes in which one process sends a string message to a second process, and the second process reverses the case of each character in the message and sends it back to the first process.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
// Parent: reads from P1_READ, writes on P1_WRITE
// Child: reads from P2_READ, writes on P2_WRITE
#define P1_READ 0
#define P2_WRITE 1
#define P2_READ 2
#define P1_WRITE 3
// the total number of pipe *pairs* we need
#define NUM_PIPES 2
/*
toggleString accepts an a pointer to char array, allocates size for the
string to be toggled,
copys the argument into a string, loops through the string and for every
uppercase character
we set it to its lower case counterpart and vice versa, returning the
toggled string
*/
char *toggleString(char *argv){
int i; /* Declare counter */
char *str = malloc(sizeof(argv[1])); /* Declare array sizeof input */
strcpy(str, argv); /* Copy String to char array */
for(i=0;str[i]!='\0';i++) { //Loop through length of string
if(str[i]>='A'&&str[i]<='Z'){ //if the array at i is uppercase
str[i]+=32; //Make it lower case
} else if (str[i]>='a'&&str[i]<='z') {// if the array at i is lowercase
str[i]-=32; //Make it uppercase
}
}
return str;
}
/*
int inputValidation accept and integer (number of arugments) and a
pointer to the cmd line input array
We check to see if the command line input contains the minimal number of
arugments and check to see
whether or not the user input contains at least one reversible haracter,
if all goes well we return 0
*/
int inputValidation(int argc, char *argv[]){
int i; //Declare counter variable
bool c = false; //Declare boolean flag using imported <stdbool.h>
char str[strlen(argv[1])]; //Declare str
strcpy(str, argv[1]); //copy argument into str
if (argc != 2) { // check to see if we have enough arguments to
continue
// Prompt user of correct usage
fprintf(stderr, "\nUsage: %s <string> or <'string 1, string 2', ...,
string n'> for multiple strings\n", argv[0]);
exit(EXIT_FAILURE); //Exit on improper input
} else {
//loop through our string
for(i=0;i<strlen(str);i++) {
//if any any char is a reversible character
if(isalpha((int) str[i])){
c = true; //set the flag to true
}
}
if(c == false){ //If flag is false input does not contain any
reversible charachters
printf("\nSorry, The string you entered did NOT contain any
Alphabetical Characters\nRun me again, with at least 1 Alphabetical
character\n\n");
exit(EXIT_FAILURE); //Exit on improper input
}
return (0);
}
}
/*
Main takes input from command line, calls input validation to make sure of
proper input,
then creates the pipes we will need and the forks the child process, Parent
and Child
execute they're respective code
*/
int main(int argc, char *argv[]) {
assert(argc>1);
int fd[2*NUM_PIPES]; //Declare int[] of file descriptors
int len, i; //Declare length and integer for count
pid_t pid; //Declare process id
char parent[strlen(argv[1])]; //Declare Parent array
char child[strlen(argv[1])]; //Declare Child array
if(inputValidation(argc, argv) == 0) /* Check for proper input */
strcpy(parent, argv[1]);
// create all the descriptor pairs we need
for (i=0; i<NUM_PIPES; ++i)
{
if (pipe(fd+(i*2)) < 0)
{
perror("Failed to allocate pipes");
exit(EXIT_FAILURE);
}
}
// fork() returns 0 for child process, child-pid for parent process.
if ((pid = fork()) < 0)
{
perror("Failed to fork process");
return EXIT_FAILURE;
}
//////////////////////////////Childs Code
BEGINS//////////////////////////////////
// if the pid is zero, this is the child process
if (pid == 0)
{
// Child. Start by closing descriptors we
// don't need in this process
close(fd[P1_READ]);
close(fd[P1_WRITE]);
// used for output
pid = getpid();
// wait for parent to send us a value
len = read(fd[P2_READ], &child, len);
if (len < 0)
{
perror("Child: Failed to read data from pipe");
exit(EXIT_FAILURE);
}
else if (len == 0)
{
// not an error, but certainly unexpected
fprintf(stderr, "Child: Read EOF from pipe");
}
else
{
// report pid to console
printf("Child(%d): Recieved Message\n\nChild(%d): Toggling Case and
Sending to Parent\n",pid, pid);
// send the message to toggleString and write it to pipe//
if (write(fd[P2_WRITE], toggleString(child), strlen(child)) < 0)
{
perror("Child: Failed to write response value");
exit(EXIT_FAILURE);
}
}
// finished. close remaining descriptors.
close(fd[P2_READ]);
close(fd[P2_WRITE]);
return EXIT_SUCCESS;
}
//child code ends///
//////////////////////////////Parent Code
BEGINS//////////////////////////////////
// Parent. close unneeded descriptors
close(fd[P2_READ]);
close(fd[P2_WRITE]);
// used for output
pid = getpid();
// send a value to the child
printf("\nParent(%d): Sending %s to Child\n\n", pid, argv[1]);
if (write(fd[P1_WRITE], argv[1], strlen(argv[1])) != strlen(argv[1]))
{
perror("Parent: Failed to send value to child ");
exit(EXIT_FAILURE);
}
// now wait for a response
len = read(fd[P1_READ], &parent, strlen(parent));
if (len < 0)
{
perror("Parent: failed to read value from pipe");
exit(EXIT_FAILURE);
}
else if (len == 0)
{
// not an error, but certainly unexpected
fprintf(stderr, "Parent(%d): Read EOF from pipe", pid);
}
else
{
// report what we received
printf("\nParent(%d): Received %s from Child\n\n", pid, parent);
}
// close down remaining descriptors
close(fd[P1_READ]);
close(fd[P1_WRITE]);
// wait for child termination
wait(NULL);
return EXIT_SUCCESS;
}
//////////////////////////////Parent Code
ENDS//////////////////////////////////
This works:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#define P1_READ 0
#define P2_WRITE 1
#define P2_READ 2
#define P1_WRITE 3
#define NUM_PIPES 2
static
char *toggleString(char *argv)
{
int i;
char *str = malloc(strlen(argv) + 1); /* Key Fix */
strcpy(str, argv);
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] >= 'A' && str[i] <= 'Z')
{
str[i] += 32;
}
else if (str[i] >= 'a' && str[i] <= 'z')
{
str[i] -= 32;
}
}
return str;
}
static
int inputValidation(int argc, char *argv[])
{
bool c = false;
char str[strlen(argv[1])];
strcpy(str, argv[1]);
if (argc != 2)
{
fprintf(stderr, "\nUsage: %s <string> or <'string 1, string 2', ..., string n'> for multiple strings\n", argv[0]);
exit(EXIT_FAILURE);
}
else
{
for (size_t i = 0; i < strlen(str); i++)
{
if (isalpha((int)str[i]))
{
c = true;
}
}
if (c == false)
{
printf("\nSorry, The string you entered did NOT contain any"
" Alphabetical Characters\nRun me again, with at least 1 Alphabetical"
" character\n\n");
exit(EXIT_FAILURE);
}
return(0);
}
}
int main(int argc, char *argv[])
{
assert(argc > 1);
int fd[2 * NUM_PIPES];
int len, i;
pid_t pid;
char parent[strlen(argv[1])];
char child[strlen(argv[1])];
if (inputValidation(argc, argv) == 0)
strcpy(parent, argv[1]);
for (i = 0; i < NUM_PIPES; ++i)
{
if (pipe(fd + (i * 2)) < 0)
{
perror("Failed to allocate pipes");
exit(EXIT_FAILURE);
}
}
if ((pid = fork()) < 0)
{
perror("Failed to fork process");
exit(EXIT_FAILURE);
}
if (pid == 0)
{
close(fd[P1_READ]);
close(fd[P1_WRITE]);
pid = getpid();
len = read(fd[P2_READ], child, sizeof(child));
if (len < 0)
{
perror("Child: Failed to read data from pipe");
exit(EXIT_FAILURE);
}
else if (len == 0)
{
fprintf(stderr, "Child: Read EOF from pipe\n");
}
else
{
child[len] = '\0';
printf("Child(%d): Received Message [%s]\nChild(%d): Toggling Case and Sending to Parent\n", pid, child, pid);
char *toggled = toggleString(child);
printf("Child(%d): Sending [%s]\n", pid, toggled);
if (write(fd[P2_WRITE], toggled, len) < 0)
{
perror("Child: Failed to write response value");
exit(EXIT_FAILURE);
}
free(toggled);
}
close(fd[P2_READ]);
close(fd[P2_WRITE]);
return EXIT_SUCCESS;
}
close(fd[P2_READ]);
close(fd[P2_WRITE]);
pid = getpid();
printf("\nParent(%d): Sending [%s] to Child\n\n", pid, argv[1]);
len = strlen(argv[1]);
if (write(fd[P1_WRITE], argv[1], len) != len)
{
perror("Parent: Failed to send value to child");
exit(EXIT_FAILURE);
}
len = read(fd[P1_READ], parent, sizeof(parent));
if (len < 0)
{
perror("Parent: failed to read value from pipe");
exit(EXIT_FAILURE);
}
else if (len == 0)
{
fprintf(stderr, "Parent(%d): Read EOF from pipe\n", pid);
}
else
{
parent[len] = '\0';
printf("\nParent(%d): Received [%s] from Child\n\n", pid, parent);
}
close(fd[P1_READ]);
close(fd[P1_WRITE]);
wait(NULL);
return EXIT_SUCCESS;
}
It was painful extracting your code from your comments, and the split over multiple line strings, and so on. The toggleString() function was broken — allocating 1 byte and then copying a string over that. The other code was not careful about null-terminating strings and handling them. These are basically the problems diagnosed in the comments.
Sample run:
$ pp53 'AbSoLuTeLy GlOrIoUs'
Parent(5209): Sending [AbSoLuTeLy GlOrIoUs] to Child
Child(5210): Received Message [AbSoLuTeLy GlOrIoUs]
Child(5210): Toggling Case and Sending to Parent
Child(5210): Sending [aBsOlUtElY gLoRiOuS]
Parent(5209): Received [aBsOlUtElY gLoRiOuS] from Child
$

Sending and receiving character array using piping through argv in C

So, I'm trying to create a pipe that sends char arrays back and forth through pipes that connect through argv[]. Right now, I'm stuck at receiving the array (param which is sent to c_param from the parent to the child.) in interface.c to receiving the characters 3 and 5 at db.c. I know that 3 and 5 are the index for argv[] that my pipes are at, but I'm not sure how to take that and print out my message in db.c.
interface.c creates the pipes, forks into a parent process and a child process. The char array param is transfered to the child process to char array c_param. Using snprintf, I made my pipe into a char to send using execl with my char array c_param.
interface.c:
int main (int argc, char *argv[])
{
int to_Child[2];
int to_Parent[2];
int id, toChildPipe, toParentPipe, err;
char param[100] = "This is the parameter!";
char sendPipe[100];
char recPipe[100];
/*CREATING PIPE*/
toChildPipe = pipe(to_Child);
toParentPipe = pipe(to_Parent);
if(toChildPipe == -1 || toParentPipe == -1)
{
printf ("Error on pipe creation: %d", errno);
exit (1);
}
/*Creating Child Process*/
id = fork();
if(id == 0)
{
/**
*
* IN THE CHILD Process
*
*/
close(to_Child[1]); //reading
close(to_Parent[0]); //writing
char c_param[100];
toChildPipe = read(to_Child[0], c_param, 100);
if (toChildPipe == -1)
{
//If failed
printf("Error on read from pipe from parent: %d\n",errno);
//exit with error
exit(2);
}//Error pipe from parent
snprintf(sendPipe,sizeof(sendPipe), "%d",to_Parent[0]);
snprintf(recPipe,sizeof(recPipe), "%d",to_Child[0]);
err = execl("./db","db",sendPipe,recPipe,(char *)0);
if(err == -1)
{
printf("Error on execl: %d\n", errno);
}//Error execl
toChildPipe = read(to_Child[0], c_param, 100);
if (toChildPipe == -1)
{
//If failed
printf("Error on read from pipe from parent: %d\n",errno);
//exit with error
exit(2);
}//Error pipe from parent
}//CHILD PROCESS
else if (id > 0)
{
/**
*
*IN THE PARENT PROCESS
*
*/
close(to_Child[0]); //writing
close(to_Parent[1]); //reading
toChildPipe = write(to_Child[1],param,100);
if(toChildPipe == -1)
{
printf("Error on write to pipe: %d", errno);
exit(3);
}
/*Piping was successful!*/
exit(0);
}//PARENT PROCESS
else
{
exit(4);
}
}
db.c started up from interface.c execl and should receive the parameters over argv[], which then should print it out.
db.c
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
FILE *finput;
int j = 0;
int fd;
int toChildPipe;
char c_param[100];
if(argc > 1)
{
for(j ; j < argc ; j++)
printf("argv = %s\n", argv[j]);
printf("argc = %d\n",argc);
}
fd = atoi(argv[1]);
printf("Statement: %s\n", argv[fd]);
strcpy(c_param, argv[3]);
printf("filename: %s\n", c_param);
}
This is the current output I'm getting, I'm aware that 5 and 3 are the indexes I need to send a message and receive the message that I'm currently trying to print in db.c
output(db.c):
argv = db
argv = 5
argv = 3
argc = 3
Statement: TERM=xterm
I hope I gave you enough information, I appreciate any help you are willing to give me. Thank you in advance!
There were lots of little things wrong. Your biggest problems were your assumptions/assertions in db.c about the parameters passed to it by interface.c — there was a total mismatch between what was passed and what was expected. There was also a good deal of extraneous code in interface.c. In particular, the child read from the pipe before executing db, so there was nothing left on the pipe for db to read.
Here's the 'fixed' code, with some debug code still in place.
interface.c
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
int to_Child[2];
int to_Parent[2];
int id;
char param[100] = "This is the parameter!";
char sendPipe[100];
char recPipe[100];
if (pipe(to_Child) == -1 || pipe(to_Parent) == -1)
{
printf("Error on pipe creation: %d", errno);
exit(1);
}
printf("Pipes: C(%d,%d), P(%d,%d)\n", to_Child[0], to_Child[1], to_Parent[0], to_Parent[1]);
id = fork();
if (id == 0)
{
close(to_Child[1]); // Child does not write to itself
close(to_Parent[0]); // Child does not read what it writes
snprintf(sendPipe, sizeof(sendPipe), "%d", to_Parent[1]);
snprintf(recPipe, sizeof(recPipe), "%d", to_Child[0]);
execl("./db", "db", sendPipe, recPipe, (char *)0);
fprintf(stderr, "Error on execl: %d\n", errno);
exit(2);
}
else if (id > 0)
{
close(to_Child[0]); // Parent does not read childs input
close(to_Parent[1]); // Parent does not
int nbytes = write(to_Child[1], param, 100);
if (nbytes == -1)
{
fprintf(stderr, "Error on write to pipe: %d\n", errno);
exit(3);
}
close(to_Child[1]);
if ((nbytes = read(to_Parent[0], param, 100)) <= 0)
{
fprintf(stderr, "Error on read from pipe: %d\n", errno);
exit(5);
}
printf("Data from pipe: [%.*s]\n", nbytes, param);
exit(0);
}
else
{
perror("fork failed");
exit(4);
}
}
### db.c
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("argc = %d\n", argc);
for (int j = 0; j < argc; j++)
printf("argv[%d] = %s\n", j, argv[j]);
if (argc != 3)
{
fprintf(stderr, "Usage: %s write-fd read-fd\n", argv[0]);
return 1;
}
int ofd = atoi(argv[1]);
int ifd = atoi(argv[2]);
printf("ifd = %d; ofd = %d\n", ifd, ofd);
char c_param[100];
int nbytes = read(ifd, c_param, sizeof(c_param));
if (nbytes <= 0)
{
fprintf(stderr, "Error: failed to read any data (%d)\n", errno);
return 1;
}
printf("Child: [%.*s]\n", nbytes, c_param);
assert(strlen(c_param) + sizeof(" - sent back to parent") <= sizeof(c_param));
strcat(c_param, " - sent back to parent");
if (write(ofd, c_param, nbytes) != nbytes)
{
fprintf(stderr, "Error: failed to write all the data (%d)\n", errno);
return 1;
}
return 0;
}
Sample run
Pipes: C(3,4), P(5,6)
argc = 3
argv[0] = db
argv[1] = 6
argv[2] = 3
ifd = 3; ofd = 6
Child: [This is the parameter!]
Data from pipe: [This is the parameter! - sent back to parent]
Note that the code reports errors to standard error (that's what it is for). It also delimits the printed data which can make it easier to spot
unexpected problems. It doesn't assume that the data is null padded; it limits the length printed to the length read, though in fact the data has numerous nulls at the end.

Using pipes to synchronize file-writing between processes

I have something that I've been staring at for most of the night and can't figure out. I'm writing code in C that is supposed to use pipes to pass a byte back and forth, allowing me to switch between a parent and child process that will take turns writing a string to a file. Here's my code:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int fd[2];
int fd2[2];
char token = 'a';
int file = open("output.txt", O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR);
if (pipe(fd) == -1 || pipe(fd) == -1)
{
printf("Pipe failed");
return(-1);
}
pipe(fd2);
int pid = fork();
int i;
int j;
write(fd[1], token, 1);
if (pid) // Parent enters here
{
for (i = 0; i < 100;)
{
if (read(fd[0], token, 1) != -1)
{
write(file, "ppppppp", 7);
i++;
write(fd2[1], token, 1);
}
//usleep(500000);
}
wait();
}
else if (pid == 0) // Child enters here
{
for (j = 0; j < 100;)
{
if (read(fd2[0], token, 1) != -1)
{
write(file, "ccccc", 5);
j++;
write(fd[1], token, 1);
}
//usleep(500000);
}
}
else // Error creating child
{
exit (-1);
}
close(file);
return 0;
}
I know the writing to a file works when I don't use the pipes, but now I'm getting an infinite loop and I don't know what the problem is.
I figured it out! Funny how small things make all the difference.

Resources