在c中被阻止的过程

时间:2012-12-02 17:11:08

标签: c linux operating-system

我正在编写一些代码来创建一个被阻塞然后结束的进程,我必须能够通过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);
}

它应该很容易,因为它只是一个被阻止的小程序,但我想我走在圈子里。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

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") 上方的<{1>} 移至wait(),因此您应该在父块等待孩子之前看到它。

编辑:此外,请加入<unistd.h>。虽然不是严格要求程序工作(在大多数系统上),但这样做可以为丢失和/或输入错误的函数参数等事项提供更好的编译时错误报告。

答案 1 :(得分:1)

man sleep

man wait

您应该在sleep()中将秒数作为参数。

waitsleep包含<unistd.h>