2q8c Write a C program (that compiles and runs on turning) to perform the follow
ID: 670981 • Letter: 2
Question
2q8c
Write a C program (that compiles and runs on turning) to perform the following: For each command-line argument use fork()to create a child process to handle that argument. Each child process should determine if the command-line argument it Is processing is a valid filename. If not, or if the child process cannot open or read the file, the child process should return an exit status of-1. If the child process can read the file, it should count the number of characters in the file and return an exit status of 0 if there are an even number of characters, or 1 if there are an odd number of characters in the file. The parent process should cause all the child processes to execute in parallel and examine their return values to determine whether, overall, there is an even or odd number of characters in all the files (files that did not exist/could not be read should be excluded). The parent process should print (to standard output) "Even" if there were an even number of characters, or "Odd" if there were an odd number of characters. It should then exit with a status of 0 if the result was even, or 1 if the result was odd.Explanation / Answer
#include <stdio.h>
#include <sys/types.h>
void parse(char *line, char **argv)
{
while (*line != '')
{
while (*line == ' ' || *line == ' ' || *line == ' ')
*line++ = '';
*argv++ = line;
while (*line != '' && *line != ' ' &&
*line != ' ' && *line != ' ')
line++;
}
*argv = '';
}
void execute(char **argv)
{
pid_t pid;
int status;
if ((pid = fork()) < 0)
{ /* fork a child process */
printf("*** ERROR: forking child process failed ");
exit(1);
}
else if (pid == 0)
{
if (execvp(*argv, argv) < 0) {
printf("*** ERROR: exec failed ");
exit(1);
}
}
else { /* for the parent: */
while (wait(&status) != pid) /* wait for completion */
;
}
}
void main(void)
{
char line[1024];
char *argv[64];
while (1) {
printf("Shell -> ");
gets(line);
printf(" ");
parse(line, argv);
if (strcmp(argv[0], "exit") == 0)
exit(0);
execute(argv);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.