Linux/Code/jincheng.c
2025-05-27 16:41:18 +08:00

39 lines
771 B
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.

/***************************************************
子进程每隔1秒打印一次apple父进程每隔2秒打印一次hello。
****************************************************/
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
// 创建子进程
pid_t pid = fork();
// 错误处理
if (pid < 0)
{
printf("创建子进程失败\n");
return -1;
}
// 子进程
else if (pid == 0)
{
while (1) {
printf("apple\n");
sleep(1); // 每隔1秒打印一次apple
}
}
// 父进程
else
{
while (1) {
printf("hello\n");
sleep(2); // 每隔2秒打印一次hello
}
}
return 0; // 程序结束
}