#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int status;
FILE *src_file, *dst_file;
char ch;
int i = 0;
src_file = fopen("original.jpg","rb");
if (src_file == NULL) {
printf("Failed to open the file!\n");
exit(-1);
}
dst_file = fopen("copy.jpg", "wb");
if (dst_file == NULL) {
printf("Failed to create the new file!\n");
fclose(src_file);
exit(-1);
}
pid = fork();
if (pid == 0) {
while(fread(&ch,sizeof(char),1,src_file)) {
if (i >= 1024) {
fwrite(&ch,sizeof(char),1,dst_file);
}
i++;
}
printf("Child process ends.\n");
exit(0);
}
else {
while(fread(&ch,sizeof(char),1,src_file)) {
if (i < 1024) {
fwrite(&ch,sizeof(char),1,dst_file);
}
i++;
}
wait(&status);
printf("Parent process ends, child status: %d\n", status);
}
fclose(src_file);
fclose(dst_file);
return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int status;
pid = fork();
if (pid == 0) {
printf("child process\n");
sleep(10);
printf("child process exit\n");
} else if (pid > 0) {
printf("parent process\n");
while (1) {
if (waitpid(pid, &status, WNOHANG) == pid) {
printf("child process exit status:%d\n", status);
break;
}
printf("parent process working\n");
sleep(1);
}
} else {
printf("fork error\n");
}
return 0;
}
创建孤儿进程:
```c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int main() {
pid_t pid = fork();
if(pid == -1) {
printf("error");
} else if(pid == 0) {
sleep(10);
} else {
exit(0);
}
return 0;
}
创建僵尸进程:
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int main() {
pid_t pid = fork();
if(pid == -1) {
printf("error");
} else if(pid == 0) {
printf("I'm child process, pid=%d\n", getpid());
exit(0);
} else {
printf("I'm parent process, pid=%d\n", getpid());
sleep(10);
}
return 0;
}