apue-intro

1.read和write系统调用

read()write()系统调用非常相似。它们都需要三个参数:一个文件描述符fd一个内存区的地址buf(该缓冲区包含接受的数据或者要传送的数据的存放位置)以及一个数count(指定应该传送多少字节)

两个系统调用都返回所成功传送的字节数

#include "apue.h"

#define	BUFFSIZE	4096

int main(void)
{
	int		n;
	char	buf[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)
{
	char	buf[MAXLINE];	/* from apue.h */
	pid_t	pid;
	int		status;

	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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值