41 lines
950 B
C
41 lines
950 B
C
// Create a program that creates a child process using fork.
|
|
// The parent and child processes should count from 0 to N, printing every STEP.
|
|
// N and step are supplied via command line arguments.
|
|
#include <stdio.h>
|
|
#include <stdlib.h> // exit
|
|
#include <unistd.h> // fork, sleep
|
|
#include <sys/wait.h> // wait
|
|
|
|
int count(char *who, int n, int step){
|
|
// count from 0 to print every step
|
|
for (int i = 0; i <= n; i++){
|
|
if (i % step == 0)
|
|
printf("%s:\t%d\n", who, i);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int main(int argc, char *argv[]){
|
|
if (argc != 3){
|
|
printf("Usage: %s N STEP\n", argv[0]);
|
|
exit(1);
|
|
}
|
|
|
|
int N = atoi(argv[1]);
|
|
int STEP = atoi(argv[2]);
|
|
int status;
|
|
int pid;
|
|
|
|
if ((pid = fork()) == 0){
|
|
count("child", N, STEP);
|
|
exit(0);
|
|
}
|
|
else if (pid == -1){
|
|
printf("fork failed.\n");
|
|
exit(2);
|
|
}
|
|
|
|
count("parent", N, STEP);
|
|
return 0;
|
|
}
|