您的位置:首页 > 运维架构 > Linux

linux 进程学习笔记-暂停进程

2015-11-23 14:31 453 查看
<!--[if !supportLists]-->Ÿ <!--[endif]-->暂停进程

int pause()

其会挂起当前进程直到有信号来唤醒或者进程被结束。

随便提一下,如果你仅仅需要简单地暂停一下(press any key  to continue...), 可以使用 system("pause")这个系统调用,甚至是getch()之类的。

下面这个demo有点晦涩,需要一些“信号”的知识。你可以阅读完“进程间通信——信号”后再回过头来看。其利用alarm(10)让系统再10秒后给自己发一个SIGALRM信号,然后暂停进程,10秒后,进程收到信号后被唤醒。

#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <time.h>

void catcher( int sig ) {
printf( "Signal catcher called for signal %d\n", sig );
}

void showtime( ) {
time_t t;
time(&t);
printf( "the time is %s\n", ctime(&t) );
}

int main()  {

struct sigaction sigact;

sigemptyset( &sigact.sa_mask );
sigact.sa_flags = 0;
sigact.sa_handler = catcher;
sigaction( SIGALRM, &sigact, NULL );

alarm( 10 );

printf("before pause, ");
showtime ();

pause();

printf("after pause, ");
showtime ();

return 0;
}
输出如下:
before pause, the time is Thu Jun 23 17:12:25 2011
signal catcher called for signal 14
after pause, the time is Thu Jun 23 17:12:35 2011

unsigned sleep(unsigned seconds)
int usleep(useconds_t useconds)
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
sleep系列函数都是让进程挂起一段时间,sleep只能精确到秒,usleep能精确到微妙,而nanosleep传说精度更高。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: