您的位置:首页 > 其它

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

2015-11-29 00:31 645 查看

process

一、environ.c

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

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

printf("MY_VER=%s\n", getenv("MY_VER"));
setenv("MY_VER", "1.1", 0);
printf("MY_VER=%s\n", 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也是存储在动态申请的内存里。




二、environvar.c

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

return 0;
}




简单打印环境变量表

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 \n", getpid());
pipe_fd = open(FIFO_NAME, open_mode);
printf("Process %d result %d\n", 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\n", getpid(), bytes);
exit(EXIT_SUCCESS);
}




四、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 \n",
FIFO_NAME);
exit(EXIT_FAILURE);
}
}

printf("Process %d opening FIFO O_WRONLY\n", getpid());
pipe_fd = open(FIFO_NAME, open_mode);
printf("Process %d result %d\n", 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\n");
exit(EXIT_FAILURE);
}
bytes += res;
}
close(pipe_fd);
} else {
exit(EXIT_FAILURE);
}

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




五、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 \n");
}
exit(EXIT_SUCCESS);
}




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:\n", ac);
for(i=0;i<ac;i++)
printf("args[%d] %s\n", i, av[i]);

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




七、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 }\n",
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;
}
}
}




想想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\n"
#define PAR_MESS    "testing..\n"
#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 );
}
}
}




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

九、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\n");
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



十、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\n");
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)合在一起



十一、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\n");

/* 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\n");
}

return 0;
}




共有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()会在数据的最后附加"\0"
printf("input: %s", x);
}
return 0;
}
void inthandler(int s)
{
printf("Called with signal %d\n", s);
sleep(s * 4);
printf("done handling signal %d\n", s);
}




Ctrl-C向进程发送SIGINT信号,Ctrl-\向进程发送SIGQUIT信号。

由于设置了SA_RESETHAND,第一次执行SIGINT的处理函数时相当于执行了signal(SIGINT,SIG_DFL),所以进程第二次收到SIGINT信号后就执行默认操作,即挂起进程。

十三、sigactdemo2.c

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

void sig_alrm( int signo )
{
/*do nothing*/
}

unsigned int mysleep(unsigned int nsecs)
{
struct sigaction newact, oldact;
unsigned int unslept;

newact.sa_handler = sig_alrm;
sigemptyset( &newact.sa_mask );
newact.sa_flags = 0;
sigaction( SIGALRM, &newact, &oldact );

alarm( nsecs );
pause();

unslept = alarm ( 0 );
sigaction( SIGALRM, &oldact, NULL );

return unslept;
}

int main( void )
{
while( 1 )
{
mysleep( 2 );
printf( "Two seconds passed\n" );
}

return 0;
}




休息seconds秒后返回;或者被信号中断且信号处理函数返回后sleep()返回0。所以如果不计较返回值的话,pause()的功能相当于无限期的sleep()。

十四、exec1.c

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

int main()
{
char    *arglist[3];

arglist[0] = "ls";
arglist[1] = "-l";
arglist[2] = 0 ;//NULL
printf("* * * About to exec ls -l\n");
execvp( "ls" , arglist );
printf("* * * ls is done. bye");

return 0;
}


第二个储存程序参数的argv数组应注意两点,1、数组的第一个元素应置为程序名称2、数组应以NULL结尾



十五、forkdemo4.c

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

int main()
{
int fork_rv;

printf("Before: my pid is %d\n", getpid());

fork_rv = fork();       /* create new process   */

if ( fork_rv == -1 )        /* check for error  */
perror("fork");

else if ( fork_rv == 0 ){
printf("I am the child.  my pid=%d\n", getpid());
printf("parent pid= %d, my pid=%d\n", getppid(), getpid());
exit(0);
}

else{
printf("I am the parent. my child is %d\n", fork_rv);
sleep(10);
exit(0);
}

return 0;
}




十六、psh1.c

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

#define MAXARGS     20
#define ARGLEN      100

int execute( char *arglist[] )
{
execvp(arglist[0], arglist);
perror("execvp failed");
exit(1);
}

char * makestring( char *buf )
{
char    *cp;

buf[strlen(buf)-1] = '\0';
cp = malloc( strlen(buf)+1 );
if ( cp == NULL ){
fprintf(stderr,"no memory\n");
exit(1);
}
strcpy(cp, buf);
return cp;
}

int main()
{
char    *arglist[MAXARGS+1];
int     numargs;
char    argbuf[ARGLEN];

numargs = 0;
while ( numargs < MAXARGS )
{
printf("Arg[%d]? ", numargs);
if ( fgets(argbuf, ARGLEN, stdin) && *argbuf != '\n' )
arglist[numargs++] = makestring(argbuf);
else
{
if ( numargs 0 ){
arglist[numargs]=NULL;
execute( arglist );
numargs = 0;
}
}
}
return 0;
}




提示用户输入argv数组中的各个元素,以用户输入回车作为结束符,运行完指定的程序后,整个sh退出。

只能运行一次命令中程序

十七、waitdemo2.c 获取子进程状态

#include    <stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>

#define DELAY   10

void child_code(int delay)
{
printf("child %d here. will sleep for %d seconds\n", getpid(), delay);
sleep(delay);
printf("child done. about to exit\n");
exit(27);
}

void parent_code(int childpid)
{
int wait_rv;
int child_status;
int high_8, low_7, bit_7;

wait_rv = wait(&child_status);
printf("done waiting for %d. Wait returned: %d\n", childpid, wait_rv);

high_8 = child_status >> 8; /* 1111 1111 0000 0000 */
low_7  = child_status & 0x7F;   /* 0000 0000 0111 1111 */
bit_7  = child_status & 0x80;   /* 0000 0000 1000 0000 */
printf("status: exit=%d, sig=%d, core=%d\n", high_8, low_7, bit_7);
}

int main()
{
int  newpid;

printf("before: mypid is %d\n", getpid());

if ( (newpid = fork()) == -1 )
perror("fork");
else if ( newpid == 0 )
child_code(DELAY);
else
parent_code(newpid);
}




wait阻塞调用它的程序直到子进程结束,返回结束进程的PID,父进程通过传给wait的参数中获取子进程以何种方式退出。如果子进程调用exit退出,那么内核把exit的返回值存放到这个整数变量中的高八位,如果进程是被杀死的,那么内核将信号序号存放在这个变量的低7位,中间一位用来指明发生错误并产生了core dump。

遇到问题及解决

1.在理解代码时,对于管道实现父子进程之间通信不理解。

解决:其基本原理是这样的:假如原先在父进程中文件描述符3和4通过管道1连接起来(3是读端,4是写端),则fork创建子进程后,子进程中的文件描述符3和4也通过管道1连接起来(3是读端,4是写端)。这样一来,在父进程通过文件描述符4向管道写入内容后,在子进程中就可以通过文件描述符3从管道中读出数据(当然在父进程中也可以通过文件描述符3从管道中读出数据)。

2.看到程序猿的博客总结了一句话:重定向I/O的是shell而不是程序。

解决:看例子listargs.c

总结体会

之前看书没有很明白进程运行,通过运行代码,能够让我比较明白的了解了进程的运行方式。通过分析代码,又让我对书上所讲述的一些函数有了进一步理解,首先,主要是通过man、grep命令查看了函数,按照老师说的先找头文件,再看相关参数;其次,通过程序猿的博客总结学习了代码功能的相关内容(比如,consumer.c和producer.c是关于FIFO的管道写、读),在看大神们的学习总结时,看到了他们的学习态度,仅仅一个功能代码都是深入研究理解,和自己的差距非常大,需要继续努力。我个人能力有限,理解代码还是存在困难,但是通过学习程序猿们的博客总结的方式,是一种有效的学习方法(仅个人看法)。

参考资料

1.《linux有名管道》(http://blog.csdn.net/firefoxbug/article/details/8137762

2.《进程间通信-命名管道FIFO》(http://blog.csdn.net/xiajun07061225/article/details/8471777

3.《linux i/o重定向与管道编程》

http://blog.csdn.net/fulianzhou/article/details/48895327

http://www.cnblogs.com/zhangchaoyang/articles/2300358.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: