unsigned replace_byte(unsigned x, unsigned char b, int i)
{
return (x & ~(0xFF<<(i<<3))) | (b << (i<<3));
}
当程序满足
Hello--->1->Bye
\ \
\--->0---->2-->Bye
这种拓扑即可输出。
情况一:
Hello
1
Bye
0
2
Bye
情况二:
Hello
1
0
Bye
2
Bye
情况三:
Hello
0
1
Bye
2
Bye
`#include "csapp.h"
#define N 2int main()
{
int status, i;
pid_t pid;
char errorInfo[128];
/* Parent creates N children */
for(i=0;i<N;i++)
if ((pid = Fork()) == 0) /* Child */
exit(100+i);
/* Parent reaps N children in no particular order */
while ((pid = waitpid(-1, &status, 0)) > 0) {
if (WIFEXITED(status))
printf("child %d terminated normally with exit status=%d\n",
pid, WEXITSTATUS(status));
else if(WIFSIGNALED(status))
{
printf("child %d terminated by signal %d: ",
pid, WTERMSIG(status) );
psignal(WTERMSIG(status), errorInfo); //psignal会打印sig的信息
}
}
/* The only normal termination is if there are no more children */
if (errno != ECHILD)
unix_error("waitpid error");
exit(0);
}
fgets的定义如下:
char fgets(char buf, int bufsize, FILE *stream);
参数:
*buf: 字符型指针,指向用来存储所得数据的地址。
bufsize: 整型数据,指明buf指向的字符数组的大小。
*stream: 文件结构体指针,将要读取的文件流。
`#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>
sigjmp_buf env;
void tfgets_handler(int sig)
{
signal(SIGALRM, SIG_DFL);
siglongjmp(env, 1);
}
char *tfgets(char *buf, int bufsize, FILE *stream)
{
static const int TimeLimitSecs = 5;
signal(SIGALRM, tfgets_handler)
alarm(TimeLimitSecs);
int rc = sigsetjmp(env, 1);
if(rc == 0) return fgets(buf, bufsize, stream);
else return NULL; //alarm,time out
}`
王维臻:10分