|
先了解一下SIGALRM信号、alarm函数和pause函数。
实现方法一:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
void isr(int n)
{
return;
}
void mysleep(int nSeconds)
{
signal(SIGALRM,isr);
alarm(nSeconds); //nSeconds秒之后发送SIGALRM信号
pause(); //等待isr函数结束
return;
}
int main()
{
int nCount = 5;
while(nCount--)
{
printf("hello world\n");
mysleep(1);
}
return 0;
}
实现方法二:用vfork函数
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
void mysleep(int nSeconds)
{
pid_t pid = 0;
/** 产生子进程 */
pid = vfork();
if(pid == 0)
{
alarm(nSeconds);//alarm的默认动作是结束调用该函数的进程
pause(); //等待nSeconds之后,子进程结束,返回到父进程,实现mysleep功能
return;
}
}
int main()
{
int nCount = 5;
while(nCount--)
{
printf("hello world\n");
mysleep(1);
}
return 0;
}
实现方法三:用fork函数
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
void mysleep(int nSeconds)
{
pid_t pid = 0;
/** 产生子进程 */
pid = fork();
if(pid == 0)
{
alarm(nSeconds);//alarm的默认动作是结束调用该函数的进程
pause(); //等待nSeconds之后,子进程结束,
return;
}
else
{
wait(); //父进程一直等待着子进程结束
}
}
int main()
{
int nCount = 5;
while(nCount--)
{
printf("hello world\n");
mysleep(1);
}
return 0;
}
(责任编辑:IT) |
