I find from Stivenson (Advanced Programming Unix Environment) "How to send file descriptor by system queue"
I make next code
int size;
int p_count;
int shmid;
char *ptr;
char *shmptr;
shmid_ds ds;
key_t key = ftok("db.pid", 1 );
if (key < 0){
printf( "ftok error \n" );
exit(1);
}
if ( (shmid = shmget(key, 4096, IPC_CREAT )) < 0){
printf( "shmget error \n" );
exit(1);
}
shmptr = (char*) shmat(shmid,0,0);
if ( (size_t) shmptr == -1 )
{
printf( "shmat error: %s\n", strerror( errno) );
}
if( shmctl(shmid, IPC_STAT, &ds) < 0){
printf( "shmctl stat error: %s \n", strerror( errno) );
}
ds.shm_perm.mode = 0666;
if( shmctl(shmid, IPC_SET, &ds) < 0){
printf( "shmctl SET error: %s \n" ,strerror( errno));
}
int fd = open( "dump.txt", O_WRONLY | O_CREAT, 0666);
*(int *) shmptr = fd;
return EXIT_SUCCESS;
the file descriptor (int fd=3) was transmitted with number 3, and I can have access to file.
But if I open new file (descriptor number 3) on the next programm (who is receive file descriptor ) I dont have access to descriptor of file "dump.txt"
the next programm
int size;
int p_count;
int shmid;
char *ptr, *shmptr;
key_t key = ftok("db.pid", 1 );
if (key < 0){
printf( "ftok error \n" );
exit(1);
}
if ( (shmid = shmget(key, 0, 0 )) < 0){
printf( "shmget error: %s \n",strerror( errno) );
exit(1);
}
shmptr = (char *) shmat(shmid,0,0);
if ( (size_t) shmptr == -1 )
{
printf( "shmat error: %s \n",strerror( errno) );
}
// int fd2 = open( "dump2.txt", O_WRONLY | O_CREAT, 0666);
int fd = *(int *) shmptr ;
char * buff = "***\n";
int res = write(fd , buff , 4);
printf( "writed %d fd=%d\n",res,fd );
if (res<0)
printf( "write error: %s \n",strerror( errno) );
close(fd);
// delete shm segment
if( shmctl(shmid, IPC_RMID, 0) < 0){
printf( "shmctl error, %s \n",strerror( errno) );
}
If I uncomment string int fd2 = open( "dump2.txt", O_WRONLY | O_CREAT, 0666);
I write text to file dump2.txt.
How is correctly to send/receive file descriptor by shmemory?
can I to send socket descriptor by shared memory?