Please dont change the code just add as it ask! if I call your code this way: Th
ID: 3675028 • Letter: P
Question
Please dont change the code just add as it ask!
if I call your code this way:
The parent process should print out:
Important: printing should be done only by the parent process. The child process should not print anything.
Your output should be formatted exactly as shown (small differences in whitespace are OK). Remember to replace %u201CI. Forgot%u201D with your own name.
------------------------------------------------------------------------
// Characters from command line arguments are sent to child process
// from parent process one at a time through pipe.
// Child process counts number of characters sent through pipe.
// Child process returns number of characters counted to parent process.
// Parent process prints number of characters counted by child process.
#include <stdio.h>
int main(int argc, char **argv)
{
// set up pipe
// call fork()
if (0 /* replace 0 with test for parent vs child, delete this comment */) {
// -- running in child process --
int nChars = 0;
// Receive characters from parent process via pipe
// one at a time, and count them.
// Return number of characters counted to parent process.
return nChars;
}
else {
// -- running in parent process --
int nChars = 0;
printf("CS201 - Assignment 3 - I. Forgot ");
// Send characters from command line arguments starting with
// argv[1] one at a time through pipe to child process.
// Wait for child process to return. Reap child process.
// Receive number of characters counted via the value
// returned when the child process is reaped.
printf("child counted %d chars ", nChars);
return 0;
}
}
Explanation / Answer
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
int fd[2];
pid_t childpid;
pipe(fd);
childpid = fork();
if ( childpid == 0 )
{
int nChars = 0;
char buffer;
close(fd[1]);
while ( read(fd[0], &buffer, 1) > 0 )
nChars++;
close(fd[0]);
exit(nChars);
}
else
{
int nChars = 0;
int status;
int i;
int j;
printf("CS201 - Assignment 3 -1 FORGOT ");
close(fd[0]);
for (i = 1; i < argc; i++ )
{
for (j = 0; j < strlen(argv[i]); j++)
{
write(fd[1], &argv[i][j], 1);
}
}
close(fd[1]);
while ((childpid = waitpid(-1, &status, 0)) > 0 )
{
if ( WIFEXITED(status) )
nChars = WEXITSTATUS(status);
else
printf("Abnormal termination of child %d", childpid);
}
printf("child counted %d chars ", nChars);
return 0;
}
}