20135337——信息安全设计基础第十一周学习笔记 process#

20135337——信息安全设计基础第十一周学习笔记
process#

一、environ.c

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	printf("PATH=%s
", getenv("PATH"));
	setenv("PATH", "hello", 1);
	printf("PATH=%s
", getenv("PATH"));
#if 0
	printf("PATH=%s
", getenv("PATH"));
	setenv("PATH", "hellohello", 0);
	printf("PATH=%s
", getenv("PATH"));


	printf("MY_VER=%s
", getenv("MY_VER"));
	setenv("MY_VER", "1.1", 0);
	printf("MY_VER=%s
", getenv("MY_VER"));
#endif
	return 0;
}
  • getenv函数

1.获得环境变量值的函数

2.参数是环境变量名name,例如”HOME”或者”PATH”。如果环境变量存在,那么getenv函数会返回环境变量值,即value的首地址;如果环境变量不存在,那么getenv函数返回NULL

  • setenv函数

1.修改或添加环境变量的函数

2.将name设置成value

1.如果name在环境中不存在,那么很好办,在环境中添加这个新的变量就OK。
setenv函数必须在environment list中增加一个新的entry,然后动态申请存储空间来存储name=value,并且使entry指向该空间。 

2.如果在环境中name已经存在,那么

 (a)若overwrite非0,那么更新name的value(实质是更新环境表,指向新的value);

 (b)若overwrite为0,则环境变量name不变,并且也不出错。

setenv函数不必在environment list中增加一个新的entry。当overwrite为0, 则不必改动entry的指向;当overwrite非0, 则直接使该entry指向name=value,当然该name=value也是存储在动态申请的内存里。

20135337——信息安全设计基础第十一周学习笔记
process#

二、environvar.c

#include <stdio.h>
int main(void)
{
	extern char **environ;
	int i;
	for(i = 0; environ[i] != NULL; i++)
		printf("%s
", environ[i]);

	return 0;
}

20135337——信息安全设计基础第十一周学习笔记
process#

  • 简单打印环境变量表

  • extern char **environ;

    每个程序都有一个环境表,它是一个字符指针数组,其中每个指针包含一个以NULL结尾的C字符串的地址。全局变量environ则包含了该指针数组的地址

三、FIFO

1.FIFO不同于管道之处在于它提供一个路径名与之关联,以FIFO的文件形式存在于文件系统中。

2.FIFO严格遵循先进先出(first in first out),对管道及FIFO的读总是从开始处返回数据,对它们的写则把数据添加到末尾。它们不支持诸如lseek()等文件定位操作。

3.FIFO往往都是多个写进程,一个读进程。

consumer.c 管道写端

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>

#define FIFO_NAME "/tmp/myfifo"
#define BUFFER_SIZE PIPE_BUF


int main()
{
	int pipe_fd;
	int res;

	int open_mode = O_RDONLY;
	char buffer[BUFFER_SIZE + 1];
	int bytes = 0;

	memset(buffer, 0, sizeof(buffer));

	printf("Process %d opeining FIFO O_RDONLY 
", getpid());
	pipe_fd = open(FIFO_NAME, open_mode);
	printf("Process %d result %d
", getpid(), pipe_fd);

	if (pipe_fd != -1) {
		do {
			res = read(pipe_fd, buffer, BUFFER_SIZE);
			bytes += res;
		} while (res > 0);
		close(pipe_fd);
	} else {
		exit(EXIT_FAILURE);
	}

	printf("Process %d finished, %d bytes read
", getpid(), bytes);
	exit(EXIT_SUCCESS);
}

20135337——信息安全设计基础第十一周学习笔记
process#

四、producer.c 管道读端

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>

#define FIFO_NAME "/tmp/myfifo"
#define BUFFER_SIZE PIPE_BUF
#define TEN_MEG (1024 * 1024 * 10)

int main()
{
	int pipe_fd;
	int res;
	int open_mode = O_WRONLY;

	int bytes = 0;
	char buffer[BUFFER_SIZE + 1];

	if (access(FIFO_NAME, F_OK) == -1) {
		res = mkfifo(FIFO_NAME, 0777);
		if (res != 0) {
			fprintf(stderr, "Could not create fifo %s 
",
				FIFO_NAME);
			exit(EXIT_FAILURE);
		}
	}

	printf("Process %d opening FIFO O_WRONLY
", getpid());
	pipe_fd = open(FIFO_NAME, open_mode);
	printf("Process %d result %d
", getpid(), pipe_fd);

	if (pipe_fd != -1) {
		while (bytes < TEN_MEG) {
			res = write(pipe_fd, buffer, BUFFER_SIZE);
			if (res == -1) {
				fprintf(stderr, "Write error on pipe
");
				exit(EXIT_FAILURE);
			}
			bytes += res;
		}
		close(pipe_fd);
	} else {
		exit(EXIT_FAILURE);
	}

	printf("Process %d finish
", getpid());
	exit(EXIT_SUCCESS);
}

20135337——信息安全设计基础第十一周学习笔记
process#

五、testmf.c 演示了mkfifo函数的用法

#include  <stdio.h>
#include  <stdlib.h>
#include  <sys/types.h>
#include  <sys/stat.h>

int main()
{
	int res = mkfifo("/tmp/myfifo", 0777);
	if (res == 0) {
		printf("FIFO created 
");
	}
	exit(EXIT_SUCCESS);
}

20135337——信息安全设计基础第十一周学习笔记
process#

  • mkfifo()

1.会依参数pathname建立特殊的FIFO文件,该文件必须不存在,而参数mode为该文件的权限(mode%~umask),因此 umask值也会影响到FIFO文件的权限。Mkfifo()建立的FIFO文件其他进程都可以用读写一般文件的方式存取。当使用open()来打开 FIFO文件时,O_NONBLOCK旗标会有影响
a.当使用O_NONBLOCK 旗标时,打开FIFO 文件来读取的操作会立刻返回,但是若还没有其他进程打开FIFO 文件来读取,则写入的操作会返回ENXIO 错误代码。
b.没有使用O_NONBLOCK 旗标时,打开FIFO 来读取的操作会等到其他进程打开FIFO文件来写入才正常返回。同样地,打开FIFO文件来写入的操作会等到其他进程打开FIFO 文件来读取后才正常返回。

六、listargs.c 证明了shell并不将重定向标记和文件名传递给程序

    #include	<stdio.h>
main( int ac, char *av[] )
{
	int	i;
	printf("Number of args: %d, Args are:
", ac);
	for(i=0;i<ac;i++)
		printf("args[%d] %s
", i, av[i]);

	fprintf(stderr,"This message is sent to stderr.
");
}

20135337——信息安全设计基础第十一周学习笔记
process#

七、pipedemo.c 管道

#include	<stdio.h>
#include<stdlib.h>
#include<string.h>
#include	<unistd.h>

int main()
{
	int	len, i, apipe[2];	//apipe数组中存储两个文件的描述符
	char	buf[BUFSIZ];		
	
	if ( pipe ( apipe ) == -1 ){
		perror("could not make pipe");
		exit(1);
	}
	printf("Got a pipe! It is file descriptors: { %d %d }
", 
							apipe[0], apipe[1]);


	while ( fgets(buf, BUFSIZ, stdin) ){  //从标准输入读入数据,放到缓冲区
		len = strlen( buf );
		if (  write( apipe[1], buf, len) != len ){	 
			//向apipe[1](即管道写端)写入数据

			perror("writing to pipe");		
			break;					
		}
		for ( i = 0 ; i<len ; i++ )  //清理缓冲区
			buf[i] = 'X' ;
		len = read( apipe[0], buf, BUFSIZ ) ;	//从apipe[0](即管道读端)读数据	
		if ( len == -1 ){				
			perror("reading from pipe");		
			break;
		}
		if ( write( 1 , buf, len ) != len ){ //把从管道读出的数据再写到标准输出
			perror("writing to stdout");		
			break;					
		}
	}
}

20135337——信息安全设计基础第十一周学习笔记
process#

  • 想想who|sort是怎么实现的。who把输出送给stdout,sort从stdin中读入数据,那也就是说who的stdout和sort的stdin连成了一个。

  • result=pipe(int array[2]);array[0]是读端的文件描述符,array[1]是写端的文件描述符。

  • pipe调用首先获得两个“最低可用文件描述符”,赋给array[0]和array[1],然后再把这两个文件描述符连接起来。

八、pipedemo2.c 使用管道向自己发送数据

#include	<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>


#define	CHILD_MESS	"I want a cookie
"
#define	PAR_MESS	"testing..
"
#define	oops(m,x)	{ perror(m); exit(x); }   //还可以这样宏定义语句块

main()
{
	int	pipefd[2];		
	int	len;			
	char	buf[BUFSIZ];		
	int	read_len;

	if ( pipe( pipefd ) == -1 )  // 创建一个管道:apipe[0]读,apipe[1]写  
		oops("cannot get a pipe", 1);

	switch( fork() ){
		case -1:
			oops("cannot fork", 2);
	
		case 0:			
			len = strlen(CHILD_MESS);
			while ( 1 ){
				if (write( pipefd[1], CHILD_MESS, len) != len )
					oops("write", 3);
				sleep(5);
			}
		
		default:		
			len = strlen( PAR_MESS );
			while ( 1 ){
				if ( write( pipefd[1], PAR_MESS, len)!=len )
					oops("write", 4);
				sleep(1);
				read_len = read( pipefd[0], buf, BUFSIZ );
				if ( read_len <= 0 )
					break;
				write( 1 , buf, read_len );
			}
	}
}

20135337——信息安全设计基础第十一周学习笔记
process#

  • 在程序中。显示来从键盘到进程,从进程到管道,再从管道到进程以及从进程回到终端的数据传输流。

九、stdinredir1.c 将stdin定向到文件

#include	<stdio.h>
#include	<fcntl.h>

int main()
{
	int	fd ;
	char	line[100];

	fgets( line, 100, stdin ); printf("%s", line );
	fgets( line, 100, stdin ); printf("%s", line );
	fgets( line, 100, stdin ); printf("%s", line );

	close(0);  // 关闭标准输入流  
	fd = open("/etc/passwd", O_RDONLY);   // 打开文件,重定向
	if ( fd != 0 ){
		fprintf(stderr,"Could not open data as fd 0
");
		exit(1);
	}

	fgets( line, 100, stdin ); printf("%s", line );
	fgets( line, 100, stdin ); printf("%s", line );
	fgets( line, 100, stdin ); printf("%s", line );
}
  • close-then-open

20135337——信息安全设计基础第十一周学习笔记
process#

十、stdinredir2.c

#include	<stdio.h>
#include<stdlib.h>
#include	<fcntl.h>

//#define	CLOSE_DUP		
//#define	USE_DUP2	

main()
{
	int	fd ;
	int	newfd;
	char	line[100];

	fgets( line, 100, stdin ); printf("%s", line );
	fgets( line, 100, stdin ); printf("%s", line );
	fgets( line, 100, stdin ); printf("%s", line );

	fd = open("data", O_RDONLY);	// 首先打开文件fd,得到3
#ifdef CLOSE_DUP
	close(0);   // 关闭文件标志符0,即stdin  
	newfd = dup(fd);		
#else
	newfd = dup2(fd,0);		
#endif
	if ( newfd != 0 ){
		fprintf(stderr,"Could not duplicate fd to 0
");
		exit(1);
	}
	close(fd);	 // 关闭fd  		

	fgets( line, 100, stdin ); printf("%s", line );  
	// 从stdin=0获取字符串,此时0标记的是fd'  

	fgets( line, 100, stdin ); printf("%s", line );
	fgets( line, 100, stdin ); printf("%s", line );
}
  • open..dup2..close
  • 只是dup2(fd,0)将close(0),dup(fd)合在一起

20135337——信息安全设计基础第十一周学习笔记
process#

十一、whotofile.c 重定向到文件

#include	<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main()
{
	int	pid ;
	int	fd;

	printf("About to run who into a file
");

	 /* create a new process or quit */
	if( (pid = fork() ) == -1 ){
		perror("fork"); exit(1);
	}

	/* child does the work */
	if ( pid == 0 ){
		close(1);				/* close, */
		fd = creat( "userlist", 0644 );		/* then open */
		execlp( "who", "who", NULL );		/* and run	*/
		perror("execlp");
		exit(1);
	}

	/* parent waits then reports */
	if ( pid != 0 ){
		wait(NULL);
		printf("Done running who.  results in userlist
");
	}

	return 0;
}

20135337——信息安全设计基础第十一周学习笔记
process#

  • 共有3个基本的概念,利用它们是的Unix下的程序可以轻易地将标准输入、输出和错误信息输出连接到文件:

    a、标准输入、输出以及错误输出分别对应于文件描述符0、1、2;

    b、内核总是使用最低可用文件描述符;

    c、文件描述符集合通过exec调用传递,且不会被改变。

十二、sigactdemo.c

#include	<stdio.h>
#include<unistd.h>
#include	<signal.h>
#define	INPUTLEN	100
void inthandler();	
int main()
{
	struct sigaction newhandler;	
	sigset_t blocked;	//被阻塞的信号集
	char x[INPUTLEN];
	newhandler.sa_handler = inthandler;	
	newhandler.sa_flags = SA_RESTART|SA_NODEFER
		|SA_RESETHAND;	
	sigemptyset(&blocked);	//清空信号处理掩码
	sigaddset(&blocked, SIGQUIT);	
	newhandler.sa_mask = blocked;	
	if (sigaction(SIGINT, &newhandler, NULL) == -1)
		perror("sigaction");
	else
		while (1) {
			fgets(x, INPUTLEN, stdin);	  //fgets()会在数据的最后附加"