#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/types.h>
void swap( int * a , int * b)
{
int temp = * a;
* a = * b;
* b = temp;
}
void sort_assending( int arr[ ] , int n )
{
for ( int i = 0 ; i < n - 1 ; i++ )
{
for ( int j = 0 ; j < n - i - 1 ; j++ )
{
if ( arr[ j] > arr[ j + 1 ] )
{
swap( arr + j , arr + j + 1 ) ;
}
}
}
}
void sort_descending( int arr[ ] , int n )
{
for ( int i = 0 ; i < n - 1 ; i++ )
{
for ( int j = 0 ; j < n - i - 1 ; j++ )
{
if ( arr[ j] < arr[ j + 1 ] )
{
swap( arr + j , arr + j + 1 ) ;
}
}
}
}
int main( )
{
int n;
printf ( "Enter number of elements in an array:\n " ) ; int arr[ n] ;
for ( int i = 0 ; i < n ; i++ )
{
printf ( "Enter the %dth element : " , i
+ 1 ) ; }
pid_t pid;
pid = fork( ) ;
if ( pid < 0 )
{
printf ( "Fork failed to create a child process...!\n " ) ; }
else if ( pid == 0 )
{
// Child process execution start from here as pid = 0
printf ( "Child process execution starts: sorting in descending order\n " ) ;
sort_descending( arr , n) ;
for ( int i = 0 ; i < n ; i++ )
{
printf ( "\t \t %d Child process : %d , parent id : %d\n " , arr
[ i
] , getpid
( ) , getppid
( ) ) ; // sleep(1);
}
printf ( "Child execution finished\n " ) ; }
else
{
//waiting to start child its execution
sleep( 1 ) ;
// Parent execution starts from here
printf ( "Parent execution starts: sorting in assending order\n " ) ;
sort_assending( arr , n) ;
for ( int i = 0 ; i < n ; i++ )
{
printf ( "%d , Parent process id: %d , child id : %d , parent id : %d\n " , arr
[ i
] , getpid
( ) , pid
, getppid
( ) ) ; sleep( 5 ) ;
}
// wait(NULL);
printf ( "Parent execution finished\n " ) ; }
}
I2luY2x1ZGU8dW5pc3RkLmg+CiNpbmNsdWRlPHN0ZGlvLmg+CiNpbmNsdWRlPHN0ZGxpYi5oPgojaW5jbHVkZTxzeXMvd2FpdC5oPgojaW5jbHVkZTxzeXMvdHlwZXMuaD4KCgp2b2lkIHN3YXAoaW50ICphICwgaW50ICpiKQp7CiAgICBpbnQgdGVtcCA9ICphOwogICAgKmEgPSAqYjsKICAgICpiID0gdGVtcDsKfQp2b2lkIHNvcnRfYXNzZW5kaW5nKGludCBhcnJbXSAsIGludCBuICkKewogICAgZm9yKGludCBpID0gMCA7IGkgPCBuIC0gMSA7IGkrKykKICAgIHsKICAgICAgICBmb3IoaW50IGogPSAwIDsgaiA8IG4gLSBpIC0gMSA7IGorKykKICAgICAgICB7CiAgICAgICAgICAgIGlmKGFycltqXSA+IGFycltqICsgMV0pCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgIHN3YXAoYXJyICsgaiAsIGFyciArIGogKyAxKTsKICAgICAgICAgICAgfQogICAgICAgIH0KICAgIH0KfQoKdm9pZCBzb3J0X2Rlc2NlbmRpbmcoaW50IGFycltdICwgaW50IG4gKQp7CiAgICBmb3IoaW50IGkgPSAwIDsgaSA8IG4gLSAxIDsgaSsrKQogICAgewogICAgICAgIGZvcihpbnQgaiA9IDAgOyBqIDwgbiAtIGkgLSAxIDsgaisrKQogICAgICAgIHsKICAgICAgICAgICAgaWYoYXJyW2pdIDwgYXJyW2ogKyAxXSkKICAgICAgICAgICAgewogICAgICAgICAgICAgICAgc3dhcChhcnIgKyBqICwgYXJyICsgaiArIDEpOwogICAgICAgICAgICB9CiAgICAgICAgfQogICAgfQp9CmludCBtYWluKCkKeyAgIAogICAgaW50IG47CiAgICBwcmludGYoIkVudGVyIG51bWJlciBvZiBlbGVtZW50cyBpbiBhbiBhcnJheTpcbiIpOwogICAgc2NhbmYoIiVkIiAsICZuKTsKICAgIGludCBhcnJbbl07CiAgICBmb3IoaW50IGkgPSAwIDsgaSA8IG4gOyBpKyspCiAgICB7CiAgICAgICAgcHJpbnRmKCJFbnRlciB0aGUgJWR0aCBlbGVtZW50IDogIiAsIGkgKyAxKTsKICAgICAgICBzY2FuZigiJWQiICwgJmFycltpXSk7CiAgICB9CiAgICB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