linux下进程创建的C语言程序
编写C语言程序,使其完成:父进程创建一个子进程,子进程运行中显示当前系统的记录时钟;父进程运行时完成将1——100循环显示到标准输出流上,同时注意程序运行时控制其执行 顺序是,子进程先运行,父进程再运行。linux 环境下
想了半天还是 弄不出来
小的 刚入行
望大家 解答下 感激不尽
程序代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <signal.h>
#include <sys/types.h>
void i_xy(int x, int y)
{
printf("%c%c%d;%dH", '\033', '[', x, y);
}
void o_str(char *str)
{
/* set output mode unbuffered */
setvbuf(stdout, (char *)NULL, _IONBF, 0);
fprintf(stdout, "%s", str);
/* set output mode default-line buffered */
setvbuf(stdout, (char *)NULL, _IOLBF, 0);
}
char *gettime()
{
static char result[16+1];
time_t t;
struct tm *lt;
t =time(NULL);
lt = (struct tm *)localtime(&t);
memset(result, 0x00, sizeof(result));
sprintf(result, "%2.2d:%2.2d:%2.2d",
lt->tm_hour, lt->tm_min, lt->tm_sec);
return result;
}
void sig_int(int signo)
{
signal(SIGINT, SIG_DFL);
perror("SIGINT was caught by child, child is stopped\n");
raise(SIGINT);
}
void sig_alrm(int signo)
{
perror("SIGALRM was caught by parent, send SIGINT to child\n");
kill(0, SIGINT);
}
void showtime()
{
signal(SIGINT, sig_int);
while(1)
{
i_xy(2, 1);
o_str(gettime());
sleep(1);
}
}
int main(int argc, char *argv[])
{
int i = 0;
pid_t pid = 0;
char str[64];
system("clear");
i_xy(2,1);
pid = fork();
if(pid < 0)
{
printf("\nfork child error\n");
return -1;
}
if(pid == 0)
showtime();
usleep(1);
/* 设置时钟,如果十秒后程序没有结束,强制停止 */
alarm(10);
signal(SIGALRM, sig_alrm);
for(i = 1; i < 20; i++)
{
memset(str, 0x00, sizeof(str));
sprintf(str, "%d", i);
i_xy(2 + i, 1);
o_str(str);
sleep(1);
}
kill(0, SIGINT); /* 向进程组发送终止信号 */
return 0;
}

