A part of my answers to the Homework Problems in CS:APP

王朝other·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

8.8

A.fork()

B.longjmp()

C.setjmp()

Warning:The function execv() doesn't belongs to group B! It should be called once returns once or never returns.

8.9

x=4

x=3

x=2

8.10

Three

8.11

Five

8.12

counter = 2

8.13

Maybe like this:

Hello

0

1

Bye

1

Bye

Also,maybe so:

Hello

1

Bye

0

1

Bye

8.14

E

8.15

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>

int main(int argc,char**argv,char**envp){

if((setenv("COLUMNS","60",1))==-1){

fprintf(stderr,"setenv() error!\n");

exit(-1);

}

if((execve("/bin/ls",argv,envp))==-1){

fprintf(stderr,"execve() error!\n");

exit(-1);

}

exit(0);

}

8.16

/* $begin waitpid1 */

#include <signal.h>

#include <unistd.h>

#include <errno.h>

#include <sys/types.h>

#include <sys/wait.h>

#include <stdio.h>

#include <stdlib.h>

#define N 2

int main()

{

int status, i;

pid_t pid[N];

for (i = 0; i < N; i++)

if ((pid[i] = fork()) == 0) /* child */

pause();/*wait for a signal*/

i=0;

while((kill(pid[i++],SIGSEGV))==0);/*send SIGSEGV signal to its children*/

/* parent waits for all of its children to terminate */

i=0;

while ((pid[i] = waitpid(-1, &status, 0)) > 0 && i<N) {

if (WIFEXITED(status))

printf("child %d terminated normally\n", pid[i]);

else

printf("child %d terminated by signal %d : %s\n",

pid[i], WTERMSIG(status),sys_siglist[WTERMSIG(status)]);

i++;

}

if (errno != ECHILD){

fprintf(stderr,"waitpid error");

exit(-1);

}

exit(0);

}

/* $end waitpid1 */

8.17

#include <signal.h>

#include <stdlib.h>

#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/wait.h>

int mysystem(char*);

int mysystem(char* command){

int status;

pid_t pid;

if((pid=fork())==0){

execl("/bin/sh","sh","-c",command,NULL);

}/*notice here!Need NOT exit()!Read man pages of execl()*/

waitpid(-1,&status,0);

if(WIFEXITED(status))

return (WEXITSTATUS(status));

else

return (WTERMSIG(status));

}

int main(int argc,char **argv){

int i=mysystem(argv[1]);

printf("i= %d\n",i);

exit(i);

}

8.18

Of course, I can. In fact,the parent only receive 2 signals. When the parent receives the first SIGUSR2 signal, it calls the handler to handle it.At the same time,the second signal arrives. This signal is blocked and becomes a pending one.When the third one, the forth one and the fifth one arrive,they are all discarded simply. When handling the first one is finished, it is forced to receive the second one and handle it.That's all.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航