扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:宋宝华 来源:天极开发 2007年11月21日
关键字:
int main() { int i; if (fork() == 0) { for (i = 1; i < 3; i++) printf("This is child process\n"); } else { for (i = 1; i < 3; i++) printf("This is parent process\n"); } } |
This is child process This is child process This is parent process This is parent process |
char command[MAX_CMD_LEN]; void main() { int rtn; /* 子进程的返回数值 */ while (1) { /* 从终端读取要执行的命令 */ printf(">"); fgets(command, MAX_CMD_LEN, stdin); command[strlen(command) - 1] = 0; if (fork() == 0) { /* 子进程执行此命令 */ execlp(command, command); /* 如果exec函数返回,表明没有正常执行命令,打印错误 perror(command); exit(errorno); } else { /* 父进程,等待子进程结束,并打印子进程的返回值 */ wait(&rtn); printf(" child process return %d\n", rtn); } } } |
int clone(int (*fn)(void *), void *child_stack, int flags, void *arg); |
int variable, fd; int do_something() { variable = 42; close(fd); _exit(0); } int main(int argc, char *argv[]) { void **child_stack; char tempch; variable = 9; fd = open("test.file", O_RDONLY); child_stack = (void **) malloc(16384); printf("The variable was %d\n", variable); clone(do_something, child_stack, CLONE_VM|CLONE_FILES, NULL); sleep(1); /* 延时以便子进程完成关闭文件操作、修改变量 */ printf("The variable is now %d\n", variable); if (read(fd, &tempch, 1) < 1) { perror("File Read Error"); exit(1); } printf("We could read from the file\n"); return 0; } |
The variable is now 42 File Read Error |
unsigned int sleep(unsigned int seconds); |
void _exit(int status); |
pid_t wait(int *status); pid_t waitpid(pid_t pid, int *status, int options); |
#include <stdio.h> #include <sys/types.h> #include <sys/sem.h> #include <sys/ipc.h> void main() { key_t unique_key; /* 定义一个IPC关键字*/ int id; struct sembuf lock_it; union semun options; int i; unique_key = ftok(".", 'a'); /* 生成关键字,字符'a'是一个随机种子*/ /* 创建一个新的信号量集合*/ id = semget(unique_key, 1, IPC_CREAT | IPC_EXCL | 0666); printf("semaphore id=%d\n", id); options.val = 1; /*设置变量值*/ semctl(id, 0, SETVAL, options); /*设置索引0的信号量*/ /*打印出信号量的值*/ i = semctl(id, 0, GETVAL, 0); printf("value of semaphore at index 0 is %d\n", i); /*下面重新设置信号量*/ lock_it.sem_num = 0; /*设置哪个信号量*/ lock_it.sem_op = - 1; /*定义操作*/ lock_it.sem_flg = IPC_NOWAIT; /*操作方式*/ if (semop(id, &lock_it, 1) == - 1) { printf("can not lock semaphore.\n"); exit(1); } i = semctl(id, 0, GETVAL, 0); printf("value of semaphore at index 0 is %d\n", i); /*清除信号量*/ semctl(id, 0, IPC_RMID, 0); } |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者