/*创建的文件具有什么样的属性
*文件属主可读可写可执行,文件属组用户和其他组用户可读可执行不可写。
*/
if(creat(filename,0755)<0){
printf("create file %s failure!\n",filename);
exit(EXIT_FAILURE);
}else{
printf("create file %s success!\n",filename);
}
}
/*依次创建文件,文件名是main函数的参数列表。
*运行时应这样输入,$./文件名 file1 file2 ...
*其中文件名是编译成的可执行文件,file1,file2等是要创建的文件。
*/
int main(int argc,char *argv[]){
int i;
if(argc<2){
perror("you haven't input the filename,please try again!\n");
exit(EXIT_FAILURE);
}
for(i=1;i<argc;i++)
{
create_file(argv[i]);
}
exit(EXIT_SUCCESS);
}
功能: 创建文件file1,file2,属主可读可写可执行,文件属组用户和其他组用户可读可执行不可写
29. 阅读程序,请写出程序实现的功能。
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
pid_t pc,pr;
pc=fork();
if (pc==0) /*若为子进程*/
{
printf("this is child process with pid of %d\n",getpid());
sleep(10); /*睡眠10秒钟*/
}
else if (pc>0) /*若为父进程*/
{
pr=wait(NULL); /*等待子进程结束*/
printf("I catched a child process with pid of %d\n",pr)
}
exit(0);
}
功能: 子进程运行完休眠10s,父进程在其结束时捕捉其pid号
五、编程题(共26分)
30. 编写strcat函数(已知strcat函数的原型是char *strcat (char *strDest, const char
*strSrc); (满分10分)
(其中strDest 是目的字符串,strSrc 是源字符串。
不调用C 的字符串库函数,请编写函数 strcat。)
(该代码是百度找的,不确保正确性) #include<iostream>
#include<string>
using std::cin;
using std::cout;
using std::endl;
char* strcat(char *strDest, const char *strSrc)
{
char* tempt = strDest;
while(*strDest!='\0')
{
strDest++;
}
while(*strSrc!='\0')
{
*strDest = *strSrc;
strDest++;
strSrc++;
}
*strDest = '\0';
return tempt;
};
int main(){
char pf[]="Hello ";
const char ps[]="World!!!";
char *pr=strcat(pf,ps);
cout<<"The result word is"<<endl;
while(*pr!='\0')
{
cout<<*pr;
pr++;
}
return 0;
}
31. 使用fork()创建一个子进程,然后让其子进程暂停5s(使用了sleep()函数)。接下来对原有的父进程使用waitpid()函数,并使用参数WNOHANG使该父进程不会阻塞。若有子进程退出,则waitpid()返回子进程号;若没有子进程退出,则waitpid()返回0,并且父进程每隔一秒循环判断一次(编程可不写头文件)。(满分16分) Int main()
{
Pid_t pc, pr;
Pc=fork(); //使用fork()函数,创建了一个子进程,在子进程里pc=0,在父进程里pc=子进程的进
程//号,子进程和父进程是并行运行的。
If (pc<0)
{
Printf(“error fork\n”);
}
Else if (pc==0)
{
Sleep(5);
Exit(0);
}
Else
{
//循环测试子进程是否推出
Do
{
//调用waitpid,且父进程不阻塞
Pr=waitpid(pc ,NULL,WNOHANG);
//pc为子进程号
//NULL为不获取子进程退出时的状态
//选项WNOHANG,当子进程没有推出时返回0
//所以子进程没推出时,pr=0,子进程退出时,pr=子进程号 //若子进程还未退出,则父进程暂停1s
If (pr==0)
{
Printf(“the child process has not exited\n”); Sleep(1)
}
} while (pr==0) //子进程没退出时,pr=0.一直做循环直到pr=子进程号 //若发现子进程退出,打印相应情况
If (pr==pc)
{
printf(“get child exit_pode: %d\n”,pr);
}
Else
{
Printf(“some error occurred.\n”);
}
}
}