I am working on some code to create a process that goes blocked and then ends, I have to be able to see the blocked state with ps.
I tried with this, but my C knowledge is not good. The code doesn’t print anything.
Here it is:
#include <stdio.h>
#include <stdlib.h> //exit();
#include <unistd.h> //sleep();
int main(int argc, char *argv[]) {
createblocked();
}
int pid;
int i;
int estado;
void createblocked() {
pid = fork();
switch( pid ) {
case -1: // pid -1 error ocurred
perror("error\n");
break;
case 0: // pid 0 means its the child process
sleep(); // we put the child to sleep so the parent will be blocked.
printf("child sleeping...");
break;
default: // !=0 parent process
// wait function puts parent to wait for the child
// the child is sleeping so the parent will be blocked
wait( estado );
printf("parent waiting...\n");
printf("Child terminated.\n");
break;
}
exit(0);
}
It should be easy because its only a little program that goes blocked, but I am walking in circles I think. Any advice?
sleep() takes a parameter: the number of seconds to sleep. When you omit it, it tends to return immediately.
Also wait() takes an
int *, not anint.try this:
note: I also moved the
printf("parent waiting...\n")above the call towait(), so you should see it before the parent blocks waiting on the child.edit: Also, include
<unistd.h>. While not strictly required in order for the program to work (on most systems), doing so will give you better compile-time error reporting for things like missing and/or incorrectly-typed function arguments.