Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Gabriel Freire

fork execl retorno entre pai e filho

Recommended Posts

Boa tarde a todos,

 

Ja vou adiantando que ainda sou bem leigo no assunto portanto tentem ser o mais claro possivel nas resposta para que eu possa entender =)

 

Bom....

 

Estou com problemas para fazer um retorno entre dois programas usando o fork e execl (não sei nem se essa é a melhor forma)

 

Preciso saber se uma string passda para o programa principal corresponde ou não a um diretorio.

 

Para isso peguei um codigo na internet e fiz a seguinte função:

 

-----------------

Programa isDir

------------------

 

#include <stdio.h>
#include <sys/stat.h>

int isDir(const char *dname);

int main(int argc, char *argv[]) {

struct stat sbuf;

if (lstat(argv[1], &sbuf) == -1) {
fprintf(stderr, "lstat() Failed. %s\n", argv[1]);
exit(1);
}

if(S_ISDIR(sbuf.st_mode)) {
//printf("DIR");
return (0);
}
//printf("NO_DIR");
return (2);
}

------------------

 

estou tentando via "return" ou "exit" pegar o retorno mas não está dando certo

=/

 

------------------

Trecho do programa principal

------------------

 

pid_t pid;
int r = -50;

pid = fork();
if (pid == -1) {
fprintf(stderr, "%s: Failed to fork()\n", strerror(errno));
exit(13);
}
if(pid == 0)
{
r = execl( "isDir", "isDir", argv[1], NULL );
if(r == -1){
printf("\n404\n");
exit(404);
}
printf("\n> this:%d <\n", r);
}

------------------

 

se alguem conseguir ajudar....

 

a proposito estou usando apenas C puro

Compartilhar este post


Link para o post
Compartilhar em outros sites

http://linux.about.com/library/cmd/blcmdl3_execvp.htm

 

RETURN VALUE

If any of the exec functions returns, an error will have occurred. The return value is -1, and the global variable errno will be set to indicate the error.

 

Você precisa de algumas funçõezitas para pegar o valor de retorno do processo filho...

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int ExecAsChild(char *program, char** arg_list)
{
pid_t child_pid;

	child_pid = fork();
	if (child_pid != 0)
	{
	int r_value;
	
		wait(&r_value);
		return WEXITSTATUS(r_value);
	}
	else
	{
		execvp(program, arg_list);
		
		fprintf(stderr, "An error ocurred in execvp.\n");
		abort();
	}
}


int main(int argc, char *argv[])
{
char * args [] = {
	"teste",
	"teste",
	NULL
	};
	
	printf("Child returned: %d\n", ExecAsChild("gTeste", args));
	return 0;
}

E o programa gTeste:

#include <stdio.h>
#include <stdlib.h>


int main(int argc, char *argv[])
{
	return argc;
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

Ler manual não dói:

 

RETURN VALUE

If any of the exec() functions returns, an error will have occurred. The return value is -1, and the global variable errno will be set

to indicate the error.

 

 

 

 

 


printf("==>%s\n", program);

if (execvp(program, arg_list) == -1) {
 				   printf("%m\n");                
                    fprintf(stderr, "An error ocurred in execvp.\n");
                    abort();
			}
 			return 0;

 

 

 

 

isis@linux-45c9:~/src> ./a.out

==> ls

teste: impossível acessar teste: Arquivo ou diretório não encontrado

PAI

Child returned: 2

 

 

 

isis@linux-45c9:~/src> ./a.out pteste

==> pteste

No such file or directory

An error ocurred in execvp.

PAI

Child returned: 0

 

 

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Isis, acho que esse "if" não é necessário.

 

As funções da família exec, se eu não me engano, não retornan em caso de sucesso.

 

fz o codigo igualzinho você postou...

 

porem ele sempre me retorna:

 

 

An error ocurred in execvp.

Child returned: 0

 

Alguma ideia?

 

Muitas!

Cheque a errno e fale qual o problema!

Eu só escrevi um códigozinho de exemplo...

Compartilhar este post


Link para o post
Compartilhar em outros sites

Pois é Isis, e la está escrito que se por acaso alguma daquelas funções retornar é porque houve um erro e o valor de retorno é -1.

Logo, eu suponho que, no caso de uma chamada bem sucedida não há retorno!

Compartilhar este post


Link para o post
Compartilhar em outros sites

Ela não retorna nada em caso de sucesso porque a imagem do processo atual é substituída pela imagem do comando passado.

Se você não verificar o valor de retorno, como vai saber que houve um erro? A errno.h SEMPRE é definida em caso de sucesso.

O if está ali p/ isso, caso ninguém tenha notado.

 

http://stackoverflow.com/questions/1584956/how-to-handle-execvp-errors-after-fork

Compartilhar este post


Link para o post
Compartilhar em outros sites

Mas isis, se a função não retorna em caso de sucesso, eu não usaria um if, olhe:

 

int ExecAsChild(char *program, char** arg_list)
{
pid_t child_pid;

        child_pid = fork();
        if (child_pid != 0)
        {
        int r_value;
        
                wait(&r_value);
                return WEXITSTATUS(r_value);
        }
        else
        {
                execvp(program, arg_list);
                //tudo que está aqui em baixo será executado APENAS se a função execvp falhar!
                fprintf(stderr, "An error ocurred in execvp.\n");
                abort();
        }
}

é exatamente o mesmo que:

int ExecAsChild(char *program, char** arg_list)
{
pid_t child_pid;

        child_pid = fork();
        if (child_pid != 0)
        {
        int r_value;
        
                wait(&r_value);
                return WEXITSTATUS(r_value);
        }
        else
        {
                if (execvp(program, arg_list) == -1)
                {
                     //tudo que está aqui em baixo será executado APENAS se a função execvp falhar!
                     fprintf(stderr, "An error ocurred in execvp.\n");
                     abort();
                }
        }
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

Ahhh, ok, podia ter dito que preferia desde o começo. Fiquei procurando problemas onde não tinha, xD

No final, aquele "if" realmente não era necessário.

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.