I am trying to write a program in which the parent process will take main () arguments and send characters to them one by one for the child process through the channel (one call to write for each character). The child process will read the characters sent to it by the parent process and print the number of characters received from the parent. A child process should not use the main () arguments in any way. The child should return normally and not have a parent killing the child.
How to count arguments? Am I sending arguments one at a time and am I reaping a child?
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define size = 100;
int main(int argc, char *argv[])
{
int i, count =0;
int c;
int fdest[2];
pid_t pid;
char buffer[BUFSIZ];
if (pipe(fdest) < 0)
perror( "pipe" );
if ((pid = fork()) < 0)
{
perror( "fork" );
}
else if (pid > 0) {
close(fdest[0]);
for (i=1; i < argc; ++i)
{
for (c=0; c < strlen(argv[i]); ++c) {
write(fdest[1], &argv[i][c], 1);
}
}
close(fdest[1]);
wait(NULL);
exit(0);
} else {
close(fdest[1]);
while (read(fdest[0], &buffer, 1) > 0)
{
count++;
}
printf("\nchild: counted %d characters\n", count);
}
wait(NULL);
exit(0);
}
user249375
source
share