Why can’t I create an IPC key with the ~/. bashrc file?

Asked

Viewed 29 times

0

I was working out some school exercises and in the statement there was a question:

One can generate an IPC key with the file . bashrc?

I not knowing the answer to the question, I created a C program that tries to do exactly the same:

if((key = ftok("~/.bashrc",'A'))<0)
{
    printf("A resposta e não.\n") 
    exit(-1);
} 

And the answer is really no. But why?

1 answer

1


Let’s see...

If you change the ~:

"~/.bashrc"

... By an absolute path:

"/home/meu_usuario/.bashrc"

... Will work normally!

Example

Taking my user as jose, the code is given below (in C):

#include <sys/types.h>
#include <sys/ipc.h>
#include <stdio.h>
#include <stdlib.h>


int main( void ) {

    key_t key;

    if( ( key = ftok( "/home/jose/.bashrc",'A' ) ) < 0 ) {

        printf("Não.\n");

        exit(-1);

        } else printf("Sim.\n");

    return(0);

    }

... Which generates the following output after compiled and executed:

[jose@poseidon ˜]$ gcc -ansi -pedantic -Wall -Wextra -Werror programa.c -o exe
[jose@poseidon ˜]$ ./exe
Sim.
[jose@poseidon ˜]$ ./exe 

Explanation

Note that in C it is possible to use relative paths as well as the proper ~. But the ~, that expands to your user’s directory, always causes problems because it only expands if it is the first character of path supplied.

Inside of double quotes, other than the first character, all characters are read without special powers - with the exception of $, of `, of \ and of @.

There are some solutions and the official POSIX for shell expansions with wordexp. But it is best to put the absolute path if it is something simple and direct as in the example above.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.