PracticeDev/study_clang/fork/fork_test_ipc.c

67 lines
1.7 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*************************************************************************
> File Name : fork_test.c
> Author : TL Song
> EMail : songtianlun@frytea.com
> Created Time : Wed 23 Dec 2020 08:46:47 AM CST
************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <time.h>
/* IPC */
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/shm.h>
int main(int arg,char* argv[]) {
int i = 0;
time_t t;
struct tm *timeinfo;
// int 被 typedef为 pid_t
pid_t pid=fork();
// 当pid==0时是子进程代码运行区域。其他则是父进程运行区域。
if(pid<0) {
printf("Create child process failure ...\n");
}else if(pid==0) {
//子进程执行体
printf("Hi i am child process ,my processId is %i \n",getpid());
i = 0;
while (1) {
sleep(1);
time(&t);
timeinfo = localtime(&t);
printf("Child: %d %s\n", i++, asctime(timeinfo));
fflush(stdout);
if(i>100)
break;
}
}
else{
//父进程执行体
printf("parent process is run ,myid is %i \n",getpid());
i = 0;
while (1) {
sleep(1);
time(&t);
timeinfo = localtime(&t);
printf("Main : %d %s\n", i++, asctime(timeinfo));
fflush(stdout);
if(i>100)
break;
}
}
// 执行体结束标志
if(pid==0) {
printf("pid=%i child process end ... \n",getpid());
}
else {
// 睡眠5s,等待子先进程结束
sleep(5);
printf("pid=%i Parent process End ... \n",getpid());
}
return 0;
}