Windforce » 日志 » 操作系统上机作业1
操作系统上机作业1
Windforce 发表于 2008-10-07 18:22:24
第1题:运行例1
例1运行成功的代码:
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main(void)
{
int i;
int n = 4;
pid_t childpid;
for( i = 1 ; i < n ; i ++ )
{
if( ( childpid = fork() ) == 0 ) //子进程
break;
}
if( childpid > 0 )
sleep(1);
fprintf( stderr , "This is process %ld with parent %ld\n",(long)getpid(),(long)getppid());
return 0;
}
结果截图:

第2题:只是把第1题改了参数。
运行截图:

第3题:运行例2。
例2运行成功的代码:
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
#include<errno.h>
int main( int argc , char * argv[] )
{
pid_t childpid;
int status;
if ( (childpid = fork() ) ==-1 ) //fork出错
{
perror("This fork failed\n");
exit(-1);
}
else if( childpid == 0 ) //子进程
{
if( execvp("threadex1",NULL) < 0 ) //子进程执行另一个程序
{
perror("This exec of command failed\n");
exit(-1);
}
}
else if( childpid > 0 ) //父进程
{
pid_t apid = wait(&status); //父进程调用wait等待子进程
printf("Parent process has been waiting the %ld child process exit\n",apid);
exit(0);
}
}
运行截图:

第4题,只是将第三题改动一下而已,运行截图:

第5题:
运行成功的代码:
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main(void)
{
int i;
int n = 4;
pid_t childpid;
while( n > 0 )
{ n--;
if( ( childpid = fork() ) == 0 ) //子进程
{
fprintf( stderr , "Process %ld has been created , with parent %ld\n",(long)getpid(),(long)getppid());
}
else if( childpid > 0 )
{
break;
}
}
// fprintf( stderr , "This is process %ld with parent %ld\n",(long)getpid(),(long)getppid());
return 0;
}
运行截图:

完毕!
祝大家上机愉快~
P.S.
1.以上代码只能在linux里运行。
未装linux的同学请先去装linux,
ubuntu下载地址:http://cdimage.ubuntu.com/releases/8.04/release/ubuntu-8.04-dvd-i386.iso
fedora下载地址:http://ftp.isu.edu.tw/pub/Linux/Fedora/linux/releases/8/Fedora/i386/iso/Fedora-8-i386-DVD.iso
鉴于linux各版本的实用性,建议大家还是用虚拟机吧。我推荐的虚拟机是Virtual Box,sun公司的,很小(几十M),很好用。
Virtual Box下载地址:http://download.virtualbox.org/virtualbox/2.0.2/VirtualBox-2.0.2-36488-Win_x86.msi
2.老师推荐使用gcc在terminal里编译,我个人喜欢有图形界面的anjuta IDE,有兴趣的话大家可以去新立德软件管理包中下载安装。
- » 2007年: 怵目惊心:足球十大断腿重伤瞬间
- » 2006年: 博客评估!


