标签:uc
头文件: #include <unistd.h>
pid_t fork (void);
1. 创建一个子进程,失败返回-1。
2. 调用一次,返回两次。分别在父子进程中返回子进程的PID和0。利用返回值的不同,可以分别为父子进程编写不同的处理分支。#include <stdio.h>
#include <unistd.h>
int main (void) {
printf ("%u进程:我要调用fork()了...\n", getpid ());
pid_t pid = fork ();
if (pid == -1) {
perror ("fork");
return -1;
}
if (pid == 0) {
printf ("%u进程:我是%u进程的子进程。\n", getpid (),
getppid ());
return 0;
}
printf ("%u进程:我是%u进程的父进程。\n", getpid (), pid);
sleep (1);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int global = 100;
int main (void) {
int local = 200;
char* heap = (char*)malloc (256 * sizeof (char));
sprintf (heap, "ABC");
printf ("父进程:%d %d %s\n", global, local, heap);
pid_t pid = fork ();
if (pid == -1) {
perror ("fork");
return -1;
}
if (pid == 0) {
global++;
local++;
sprintf (heap, "XYZ");
printf ("子进程:%d %d %s\n", global, local, heap);
free (heap);
return 0;
}
sleep (1);
printf ("父进程:%d %d %s\n", global, local, heap);
free (heap);
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main (void) {
printf ("ABC");
pid_t pid = fork ();
if (pid == -1) {
perror ("fork");
return -1;
}
if (pid == 0) {
printf ("XYZ\n");
return 0;
}
sleep (1);
printf ("\n");
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main (void) {
printf ("父进程:");
int a, b, c;
scanf ("%d%d%d", &a, &b, &c);
pid_t pid = fork ();
if (pid == -1) {
perror ("fork");
return -1;
}
if (pid == 0) {
scanf ("%d%d%d", &a, &b, &c);
printf ("子进程:%d %d %d\n", a, b, c);
return 0;
}
sleep (1);
printf ("父进程:%d %d %d\n", a, b, c);
return 0;
}
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main (void) {
int fd = open ("ftab.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror ("open");
return -1;
}
const char* text = "Hello, World !";
if (write (fd, text, strlen (text) * sizeof (text[0])) == -1) {
perror ("write");
return -1;
}
pid_t pid = fork ();
if (pid == -1) {
perror ("fork");
return -1;
}
if (pid == 0) {
if (lseek (fd, -7, SEEK_CUR) == -1) {
perror ("lseek");
return -1;
}
close (fd);
return 0;
}
sleep (1);
text = "Linux";
if (write (fd, text, strlen (text) * sizeof (text[0])) == -1) {
perror ("write");
return -1;
}
close (fd);
return 0;
}
结果:Hello ,Linux !版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:uc
原文地址:http://blog.csdn.net/meetings/article/details/47123359