Friday 1 April 2016

Posix Spawn: C++ program using Posix Library

Q: Program to implement a Posix Spawn

Os: Linux Ubuntu 16.04 LTS
Compiler: g++



Code:

using namespace std;
#include <spawn.h>
#include <stdio.h>
#include <errno.h>
#include <iostream>
int main()
{
   posix_spawnattr_t X;
   posix_spawn_file_actions_t Y;
   pid_t Pid,Pid2;
   char * argv[] = {"/bin/ps","-lf",NULL};
   char * envp[] = {"PROCESSES=2"};
   posix_spawnattr_init(&X);
   posix_spawn_file_actions_init(&Y);
   char s1 []= "mkdir "; 
   char s2[] = " temp";
   char *sa1[]= {s1,s2,NULL}; 
   int v1 = posix_spawn(&Pid2,"/bin/mkdir",NULL,NULL,sa1,NULL); 
   perror("posix_spawn for mkdir");   
   posix_spawn(&Pid,"/bin/ps",&Y,&X,argv,envp);
   perror("posix_spawn for ps");
/*The perror() function produces a message on standard error describing
  the last error encountered during a call to a system or library
  function.*/
   cout << "Ps:spawned PID: " << Pid << endl;
   cout << "mkdir:spawned PID: " << Pid2 << endl;
   return(0);
}


/*Output
usr@comp:~$ g++ posix_spawn.cpp 
posix_spawn.cpp: In function ‘int main()’:
posix_spawn.cpp:13:41: warning: deprecated conversion from string constant to ‘char*’ 
[-Wwrite-strings]
    char * argv[] = {"/bin/ps","-lf",NULL};
                                         ^
posix_spawn.cpp:13:41: warning: deprecated conversion from string constant to ‘char*’ 
[-Wwrite-strings]
posix_spawn.cpp:14:34: warning: deprecated conversion from string constant to ‘char*’ 
[-Wwrite-strings]
    char * envp[] = {"PROCESSES=2"};
                                  ^
usr@comp:~$ ./a.out
posix_spawn for mkdir: Success
posix_spawn for ps: Success
Ps:spawned PID: 7451
mkdir:spawned PID: 7450
usr@comp:~$ F S UID        PID  PPID  C PRI  NI ADDR SZ WCHAN  STIME TTY          TIME CMD
0 S usr      7407  7399  0  80   0 -  6747 wait_w 23:49 pts/0    00:00:00 bash
0 R usr      7451  1687  0  80   0 -  3893 -      23:50 pts/0    00:00:00 /bin/
^C
usr@comp:~$ ls -l|grep temp
drwxrwxr-x 2 usr usr   4096 Mar 31 23:50  temp








*/

No comments:

Post a Comment