ps kill and signals C program where two child processes are created using fork()
Lab 7 – ps, kill, and signals
Part I
Use shell terminal to launch a GUI-based application to be executed in the background. Here are
examples to start image viewer gimp on CS server:
>>>>> gimp &
>>>>> gimp imagefile.ppm &
Use command kill -9 pid to terminate this application.
Part II
Repeat the above. This time, do not use the ampersand. The application is executed in fore
ground. Open another terminal. Use command ps to find out the process id of the application that
you have launched, and then use command kill -9 pid to terminate it.
Part III
Write a C program where two child processes are created using fork(). The parent process and
child processes all write into a shared file using system call write(). The file name is given from
command line.
Define three strings like this:
buf[0] = “EXAM! EXAM! EXAM!\n”;
buf[1] = “HELP! HELP! HELP!\n”;
buf[2] = “STUDY! STUDY! STUDY!\n”;
The parent process will open the file using open() before the fork. The first child will write the
content of buf[0] into the file. Then the second child will write the content of buf[1] into the file.
Finally, the parent will write the content of buf[2] into the file and close the file. Add sleep(5)
after each write() statement.
Use signal to coordinate the access to the shared file, so that the file is accessed with mutual
exclusion.
In addition to writing to the file, both parent and child processes should also write some related
information to the terminal according to what the sample shows.
Sample run:
Answer:
#include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <signal.h> #include <stdio.h> void alarming(int n){}; int main(int argc, char *argv[]){ char* buf[3]; buf[0]= "EXAM! EXAM! EXAM!\n"; buf[1]= "HELP! HELP! HELP!\n"; buf[2]= "STUDY! STUDY! STUDY!\n"; int fd1 = open(argv[1], O_CREAT | O_WRONLY | O_TRUNC, 0755); int pid1 = fork(); //parent if (pid1 > 0){ int pid2 = fork(); // second child if (pid2 == 0){ signal(SIGALRM, alarming); pause(); write(fd1, buf[1], 18); sleep(5); printf("%d has written to file: %s", getpid(), buf[1]); kill(pid2,SIGALRM); exit(0); } printf("parent opened file: %s\n", argv[1]); printf("parent created child process: %d\n", pid1); printf("parent created child process: %d\n", pid2); signal(SIGALRM, alarming); pause(); signal(SIGALRM, alarming); pause(); write(fd1, buf[2], 21); sleep(5); printf("parent has written to file: %s", buf[2]); printf("parent closed the file.\n"); } //first child else{ write(fd1, buf[0], 18); sleep(5); printf("%d has written to file: %s", getpid(), buf[0]); kill(pid1, SIGALRM); exit(0); } close(fd1); }
Leave a reply