我正在编写一些代码来创建一个阻塞的进程,然后结束,我必须能够看到ps的阻塞状态。
我试过了,但我的C语言知识不是很好。代码不会打印任何内容。
这就是它:
#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);
}
这应该很容易,因为这只是一个小程序被阻塞了,但我想我是在兜圈子。有什么建议吗?
发布于 2012-12-03 01:27:32
sleep()有一个参数:休眠的秒数。当您省略它时,它往往会立即返回。
另外,wait()接受int *
,而不是int
。
试试这个:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
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
printf("child sleeping...\n");
sleep(500); // we put the child to sleep so the parent will be blocked.
break;
default: // !=0 parent process
// wait function puts parent to wait for the child
// thechild is sleeping so the parent will be blocked
printf("parent waiting...\n");
wait(&estado);
printf("Child terminated.\n");
break;
}
exit(0);
}
注意:我还将printf("parent waiting...\n")
移到了对wait()
的调用之上,因此您应该在父级阻塞等待子级之前看到它。
编辑:另外,包含<unistd.h>
。虽然对于程序的工作(在大多数系统上)并不是严格要求的,但这样做可以为您提供更好的编译时错误报告,例如缺少和/或键入错误的函数参数。
发布于 2012-12-03 01:24:11
man sleep
man wait
您应该在sleep()
中提供秒数作为参数。
对于wait
和sleep
,包含<unistd.h>
https://stackoverflow.com/questions/13671628
复制相似问题