apue-intro
来源:互联网 发布:剑网三dbm数据那个好 编辑:程序博客网 时间:2024/05/19 07:43
1.read和write系统调用
read()和write()系统调用非常相似。它们都需要三个参数:一个文件描述符fd,一个内存区的地址buf(该缓冲区包含接受的数据或者要传送的数据的存放位置),以及一个数count(指定应该传送多少字节)。
两个系统调用都返回所成功传送的字节数
#include "apue.h"#defineBUFFSIZE4096int main(void){intn;charbuf[BUFFSIZE];while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)if (write(STDOUT_FILENO, buf, n) != n)err_sys("write error");if (n < 0)err_sys("read error");exit(0);}
2.fork函数
在Unix/Linux中用fork函数创建一个新的进程。进程是由当前已有进程调用fork函数创建,分叉的进程叫子进程,创建者叫父进程。该函数的特点是调用一次,返回两次,一次是在父进程,一次是在子进程。两次返回的区别是子进程的返回值为0,父进程的返回值是新子进程的ID。子进程与父进程继续并发运行。如果父进程继续创建更多的子进程,子进程之间是兄弟关系,同样子进程也可以创建自己的子进程,这样可以建立起定义关系的进程之间的一种层次关系。
程序包含位于内存的多个组成部分,执行程序的过程将根据需要来访问这些内容,包括文本段(text segment)、数据段(data segments)、栈(stack)和堆(heap)。文本段中存放CPU所执行的命令,数据段存放进程操作的所有数据变量,栈存放自动变量和函数数据,堆存放动态内存分配情况数据。当进程被创建时,子进程收到父进程的数据副本,包括数据空间、堆、栈和进程描述符。
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <errno.h>#include <sys/types.h>int add(int a,int b);//全局变量int global = 99;char buf[] = "Input a string: ";int main(){ pid_t pid; int val,ret; char *str; val =49; str = (char*)malloc(100*sizeof(char)); memset(str,0,100*sizeof(char)); if((pid = fork()) == -1) { perror("fork() error"); exit(-1); } if(pid == 0) //子进程 { printf("Child process start exec.\n"); global++; val++; } if(pid >0) //父进程 { sleep(10); //等待子进程执行 printf("Parent process start exec.\n"); } printf("pid=%d,ppid=%d,global=%d,val=%d\n",getpid(),getppid(),global,val); write(STDOUT_FILENO,buf,strlen(buf)); read(STDIN_FILENO,str,100); write(STDOUT_FILENO,str,strlen(str)); ret = add(global,val); printf("global+val=%d\n",ret); exit(0);}int add(int a,int b){ return (a+b);}
#include "apue.h"#include <sys/wait.h>int main(void){charbuf[MAXLINE];/* from apue.h */pid_tpid;intstatus;printf("%% ");/* print prompt (printf requires %% to print %) */while (fgets(buf, MAXLINE, stdin) != NULL) {if (buf[strlen(buf) - 1] == '\n')buf[strlen(buf) - 1] = 0; /* replace newline with null */if ((pid = fork()) < 0) {err_sys("fork error");} else if (pid == 0) {/* child */execlp(buf, buf, (char *)0);err_ret("couldn't execute: %s", buf);exit(127);}/* parent */if ((pid = waitpid(pid, &status, 0)) < 0)err_sys("waitpid error");printf("%% ");}exit(0);}
0 0
- apue-intro
- Intro
- intro
- Intro
- apue
- APUE
- apue
- APUE
- APUE
- Cookie Intro
- Python intro
- jetty intro
- reflect intro
- The intro.
- HTML5 Intro
- live555 intro
- OceanBase - intro
- Spark Intro
- Fedora22 安装VM12教程
- 关于Hashcode的作用
- 面试---i++在两个线程分别执行100次,最大值和最小值分别多少
- 使用数组实现的简单队列结构
- Android页面初始化时让控件失去焦点
- apue-intro
- matlab生成opencv需要的xml文件
- ZOJ.2405 Specialized Four-Digit Numbers【水,暴力】 2015/09/24
- 硅藻泥行业四协会上书工信部呼吁严肃硅藻泥标准审定审批
- LIB和DLL的区别与使用
- HEOI2012 朋友圈
- 盘点 DevOps 世界的杰出女性(一)
- strtoul
- poj3169