Читаем 100 Shell Programs in Unix полностью

$cc -o prg89 prg89.c

Run

$./prg89 Output is

The process id of the process is 4884

90. Program to get pid of the parent process.

$vi prg90.c

#include

#include

int main()

{

int ppid;

ppid=getppid();

printf(“The process id of the parent process

is %d\n”,ppid);

return 0;

}

Compile

$cc -o prg90 prg90.c

Run

$./prg90

Output is

The process id of the parent process is 4904

Parent and Child Process

Any running program is called a process. From the process we can create another process. There is a parent-child relationship between these two processes. The way to achieve this is by using a function called fork(). This function splits the running process into two processes at the point where fork is called. The first is known as parent and the new process created is known as child. Both the processes have same copy of the code after the point where fork() is called.

91. Program to show how fork() divide the process into two parts.

$vi prg91.c

#include

#include

int main()

{

printf(“Hello\n”);

fork(); #fork system call is used to create child

printf(“World\n”);

return 0;

}

Compile

$cc -o prg91 prg91.c

Run

$./prg91 Output is

Hello World World

92. Program to show the existence of both child and parent processes.

$vi prg92.c

#include

#include

int main()

{

int pid;

pid=fork(); #pid=pid of child (fork()

returns pid of child process)

if(pid==0)

{

#This part gets executed in child

printf(“I am child. The value of

variable pid is %d\n”, pid);

printf(“I am child and my process

id is %d\n”, getpid());

printf(“I am child and my parent process

id is %d\n”, getppid());

}

else

{

#This part gets executed in parent

printf(“I am parent. The value of pid

is %d\n”, pid);

printf(“I am parent and my process

id is %d\n”, getpid());

printf(“I am parent and my parent process

id is %d\n”, getppid());

}

return 0;

}

Compile

$cc -o prg92 prg92.c

Run

$./prg92 Output is

I am child. The value of variable pid is 0

I am child and my process id is 4985

I am child and my parent process id is 4984

I am parent. The value of pid is 4985

I am Parent and my process id is 4984

I am Parent and my parent process id is 4822

Zombie and Orphans

When we fork a new child process and the parent and the child continue to execute, there are two possibilities – either the child process ends first or the parent process ends first.

If child terminates earlier than the parent then the parent process is known as Zombie.

If parent terminates earlier than the child then the child process is known as Orphan.

93. Program to show the orphan process.

#include

#include int main()

{

int pid;

pid=fork();

if(pid==0)

{

printf(“I am child and my pid is %d\n”,getpid());

printf(“I am child and my ppid is %d\n”,getppid());

sleep(10);

printf(“\nI am child and my pid is %d”\n,getpid());

printf(“I am child and my ppid is %d\n”,getppid());

}

else

{

printf(“I am parent and my pid is %d\n”,getpid());

printf(“I am parent and my ppid is %d\n”,getppid());

}

}

Compile

$cc -o prg93 prg93.c

Run

$./prg93 Output is

I am child and my pidis 4943

I am child and my ppid is 4942

I am parent and my pid is 4942

I am parent and my ppid is 4868

[root@localhost ~]$

I am child and my pid is 4943

I am child and my ppid is 1

these two lines are display

after 10 seconds

Here parent has expired so

now child is orphan

94.  Program to show the Zombie process.

#include

#include

int main()

{

if(fork()>0)

{

sleep(20);

printf(“Parent\n”);

}

}

Compile

$cc -o prg94 prg94.c

Run

$./prg94

Output is displayed after some time

Parent

95. Program to show the division of process by fork.

#include

#include

int main()

{

int i=0,j=0,pid;

pid=fork();

if(pid==0);

{

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

printf(“%d ? ? ?”,i);

}

else

{

for(j=0;j100;j++)

printf(“%d * * *”,j);

}

printf(“\n”);

}

Compile

$cc -o prg95 prg95.c

Run

$./prg95

Output is display after some time

0 ? ? ?1 ? ? ?2 ? ? ?3 ? ? ?4 ? ? ?5 ? ? ?6 ? ? ?7 ? ? ?8 ? ? ?9 ? ?

?10 ? ? ?11 ? ? ?12 ? ? ?13 ? ? ?14 ? ? ?15 ? ? ?16 ? ? ?17 ? ? ?18 ?

? ?19 ? ? ?20 ? ? ?21 ? ? ?22 ? ? ?23 ? ? ?24 ? ? ?25 ? ? ?26 ? ? ?27

? ? ?28 ? ? ?29 ? ? ?30 ? ? ?31 ? ? ?32 ? ? ?33 ? ? ?34 ? ? ?35 ? ? ?36

? ? ?37 ? ? ?38 ? ? ?39 ? ? ?40 ? ? ?41 ? ? ?42 ? ? ?43 ? ? ?44 ? ? ?45

? ? ?46 ? ? ?47 ? ? ?48 ? ? ?49 ? ? ?50 ? ? ?51 ? ? ?52 ? ? ?53 ? ? ?54

? ? ?55 ? ? ?56 ? ? ?57 ? ? ?58 ? ? ?59 ? ? ?60 ? ? ?61 ? ? ?62 ? ? ?63

? ? ?64 ? ? ?65 ? ? ?66 ? ? ?67 ? ? ?68 ? ? ?69 ? ? ?70 ? ? ?71 ? ? ?72

? ? ?73 ? ? ?74 ? ? ?75 ? ? ?76 ? ? ?77 ? ? ?78 ? ? ?79 ? ? ?80 ? ? ?81

? ? ?82 ? ? ?83 ? ? ?84 ? ? ?85 ? ? ?86 ? ? ?87 ? ? ?88 ? ? ?89 ? ? ?90

Перейти на страницу:

Похожие книги

Компьютерные сети. 6-е изд.
Компьютерные сети. 6-е изд.

Перед вами шестое издание самой авторитетной книги по современным сетевым технологиям, написанное признанным экспертом Эндрю Таненбаумом в соавторстве со специалистом компании Google Дэвидом Уэзероллом и профессором Чикагского университета Ником Фимстером. Первая версия этого классического труда появилась на свет в далеком 1980 году, и с тех пор каждое издание книги неизменно становилось бестселлером. В книге последовательно изложены основные концепции, определяющие современное состояние компьютерных сетей и тенденции их развития. Авторы подробно объясняют устройство и принципы работы аппаратного и программного обеспечения, рассматривают все аспекты и уровни организации сетей — от физического до прикладного. Изложение теоретических принципов дополняется яркими, показательными примерами функционирования интернета и компьютерных сетей различного типа. Большое внимание уделяется сетевой безопасности. Шестое издание полностью переработано с учетом изменений, произошедших в сфере сетевых технологий за последние годы, и, в частности, освещает такие технологии, как DOCSIS, 4G и 5G, беспроводные сети стандарта 802.11ax, 100-гигабитные сети Ethernet, интернет вещей, современные транспортные протоколы CUBIC TCP, QUIC и BBR, программно-конфигурируемые сети и многое другое.

Дэвид Уэзеролл , Ник Фимстер , Эндрю Таненбаум

Учебные пособия, самоучители