/*********************************************************************************
|
* Copyright: (C) 2025 LingYun IoT System Studio
|
* All rights reserved.
|
*
|
* Filename: fork.c
|
* Description: This file is fork() example program.
|
*
|
* Version: 1.0.0(10/27/2025)
|
* Author: Guo Wenxue <guowenxue@gmail.com>
|
* ChangeLog: 1, Release initial version on "10/27/2025 10:39:48 AM"
|
*
|
********************************************************************************/
|
|
#include <stdio.h>
|
#include <stdlib.h>
|
#include <unistd.h>
|
#include <errno.h>
|
#include <string.h>
|
|
int main(void)
|
{
|
int var = 10;
|
pid_t pid;
|
|
printf("parent process pid[%d] running...\n", getpid() );
|
printf("before fork: var=%d, addr=%p\n", var, &var);
|
printf("\n");
|
|
pid = fork();
|
|
if (pid < 0)
|
{
|
printf("fork() create child process failure: %s\n", strerror(errno));
|
exit(1);
|
}
|
else if (pid == 0)
|
{
|
printf("child process pid[%d] running, parent pid is [%d]\n", getpid(), getppid());
|
var = 20; /* 子进程修改变量 */
|
printf("child process space: var=%d, addr=%p\n", var, &var);
|
}
|
else if( pid > 0 )
|
{
|
sleep(1); /* 父进程等待片刻,让子进程先执行 */
|
printf("parent process pid[%d] running, child pid is [%d]\n", getpid(), pid);
|
printf("parent process space: var=%d, addr=%p\n", var, &var);
|
}
|
|
printf("process pid[%d] exit\n\n", getpid());
|
|
return 0;
|
}
|