• Publicidad

Crear variable de entorno

¿Ya sabes lo que es una referencia? Has progresado, el nível básico es cosa del pasado y ahora estás listo para el siguiente nivel.

Crear variable de entorno

Notapor rfm » 2009-03-20 08:07 @380

Hola a todos...

Tengo un problemilla al intentar hacer system("export PID_SYNC=$pid") donde $pid es mi variable local que he sacado con $$.

Resulta que al ejecutarlo me dice la bash lo siguiente: Can't exec "export": No existe el fichero ó directorio at....

Lo mismo ocurre cuando intento hacer sytem("unset PID_SYNC").

¿Sabe alguien qué puede estar ocurriendo?

Muchas gracias.
Saludos.
rfm
Perlero nuevo
Perlero nuevo
 
Mensajes: 47
Registrado: 2007-11-09 09:00 @417

Publicidad

Notapor explorer » 2009-03-20 08:57 @415

Efectivamente, bash no puede ejecutar export porque no existe como ejecutable. Es un comando interno del propio bash. Y lo mismo con unset.

Una forma de ejecutarlos sería
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
system(bash -c 'export VAR1="Hola"; echo 2.[\$VAR1]');
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4

Así, bash con la opción -c interpreta los comandos pasados como una cadena de caracteres. Pero... a partir de ese momento, desaparece el entorno modificado, pues el proceso bash que lo creó, termina:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
print "1.[" . qx(bash -c 'export VAR1=Hola; echo 2.[\$VAR1]') . "]";
print "3.[" . qx(echo 4.[\$VAR1]) . "]";
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


En este hilo, Cargar variable de entorno se comenta que no se puede modificar el entorno de un proceso desde un proceso hijo.

En otro hilo, Restricciones de system se comenta la forma de modificar el entorno de forma momentánea de los procesos hijo lanzados desde nuestro programa Perl.

La única forma que conozco de que se modifique el entorno actual es por medio de sentencias export o ejecutando scripts por medio de source (otro comando interno de bash), pero, volvemos a las mismas: los procesos hijos no pueden modificar el entorno de los padres.

Hay que consultar el unix faq, que en la pregunta 2.8 dice:

Subject: How do I ... and have that change affect my current shell?
Date: Thu Mar 18 17:16:55 EST 1993

2.8) How do I {set an environment variable, change directory} inside a program or shell script and have that change affect my current shell?

In general, you can't, at least not without making special arrangements. When a child process is created, it inherits a copy of its parent's variables (and current directory). The child can change these values all it wants but the changes won't affect the parent shell, since the child is changing a copy of the original data.

Some special arrangements are possible. Your child process could write out the changed variables, if the parent was prepared to read the output and interpret it as commands to set its own variables.

Also, shells can arrange to run other shell scripts in the context of the current shell, rather than in a child process, so that changes will affect the original shell.

For instance, if you have a C shell script named "myscript":

cd /very/long/path
setenv PATH /something:/something-else

or the equivalent Bourne or Korn shell script

cd /very/long/path
PATH=/something:/something-else export PATH

and try to run "myscript" from your shell, your shell will fork and run the shell script in a subprocess. The subprocess is also running the shell; when it sees the "cd" command it changes *its* current directory, and when it sees the "setenv" command it changes *its* environment, but neither has any effect on the current directory of the shell at which you're typing (your login shell, let's say).

In order to get your login shell to execute the script (without forking) you have to use the "." command (for the Bourne or Korn shells) or the "source" command (for the C shell). I.e. you type

. myscript

to the Bourne or Korn shells, or

source myscript

to the C shell.

If all you are trying to do is change directory or set an environment variable, it will probably be simpler to use a C shell alias or Bourne/Korn shell function. See the "how do I get the current directory into my prompt" section of this article for some examples.

A much more detailed answer prepared by
[email protected] (Thomas Michanek) can be found at
ftp.wg.omron.co.jp in /pub/unix-faq/docs/script-vs-env.


Haría falta un poco más de detalle en tu pregunta para ver si se puede resolver de otra forma.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14477
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Notapor rfm » 2009-03-23 03:37 @192

Gracias por tu respuesta explorer.

Pero parece que no me funciona para solucionar mi problema en cuestión que es el siguiente:

Tengo un script que es lanzado por un servicio en determinados momentos y que es lanzado en background con diferentes parámetros cada vez.

Inicialmente es lanzado sin parámetros y se queda ejecutándose a la espera de que otra llamada al mismo script con diferentes parámetros mate el anterior proceso y solo se ejecute el nuevo.

Por eso quiero salvar el PID del primer proceso en una variable de entorno, aunque lo podría hacer en un fichero, la verdad, pero bueno, por saber las posibilidades que tenía...

Muchas gracias por vuestra labor.
Un saludo.
rfm
Perlero nuevo
Perlero nuevo
 
Mensajes: 47
Registrado: 2007-11-09 09:00 @417

Notapor explorer » 2009-03-23 04:22 @223

Pero es que el segundo programa que se ejecutase, no tendría acceso a las variables de entorno del primer programa: él corre en su propio entorno.

La solución es la que has comentado y que se ve muy bien en los sistemas Linux actuales: guardar en /var/run/ el PID del programa que se está ejecutando para que sepa el segundo que se está ejecutando y cuál es.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14477
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España


Volver a Intermedio

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 26 invitados

cron