How to disable output while a tty-writing process is in background? [duplicate] - linux

I have a method in my process that should be run only if the process is not in background.
How can I dynamically test if the current process is in background ?
Thanks

Here is what I use, for a program launched from a shell with job control (most of the shell, see below):
/* We can read from stdin if :
* - we are in foreground
* - stdin is a pipe end
*/
static int validate_stdin(void) {
pid_t fg = tcgetpgrp(STDIN_FILENO);
int rc = 0;
if(fg == -1) {
debug_printf("Piped\n");
} else if (fg == getpgrp()) {
debug_printf("foreground\n");
} else {
debug_printf("background\n");
rc = -1;
}
return rc;
}
If a session has a controlling terminal, there can be only process group in the foreground, and tcget/setpgrp is used for setting this process group id. So if your process group Id is not the process group Id of the foreground process group, then you are not in foreground.
It works if the shell has job control, as the link pointed by mouviciel says.
However, it is not always the case. For example, on embedded system using busybox, the shell can be configured with or without job control.

Check out Unix FAQ: How can a process detect if it's running in the background?
General answer is: You can't tell if you're running in the background.
But you can check if stdin is a terminal: if(isatty(0)) { ... }

Try to check availability of DISPLAY. There shown source code of xset command
How to check if Linux console screensaver has blanked screen

This sounds like a bad design. Can you tell us something about this method you're mentioning in your question? As mouviciel said, there's no reliable way.
One suggestion I have is to use the "foreground behaviour" by default and keep the "background behaviour" under a switch like -d (for daemon mode) or vice versa if your program usually runs in the background. One example of such usage is fetchmail.

Related

Close another process from node on Windows

How can I kill a process from node on Windows?
I'm making a updater. It needs close a windows executable (.exe) to download the updates. (The update process is download and overwrite). I read that this is possible with process.kill(pid[, signal])
But, How can I get the PID of the process if I know the name of the process?
According to the documentation, you simply access the property.
process.kill(process.pid, 'SIGKILL');
This is a theoretical, untested, psuedo function that may help explain what I have in mind
exec('tasklist', (err, out, code) => { //tasklist is windows, but run command to get proccesses
const id = processIdFromTaskList(processName, out); //get process id from name and parse from output of executed command
process.kill(id, "SIGKILL"); //rekt
});
Use node-windows to get pid of process you want to kill so that you can call process.kill. The library also provides an api to kill task.

How to create an execve() child process with the right tty settings to run 'vi' yet still redirect IO back to the parent process?

How do I get a forked, execve() child process that can run 'vi', etc. and redirect all IO to the parent process?
I'm trying to pass shells through from an embedded Linux process to the PC software interface connected over the network. The IO for the shell process is packaged into app-specific messages for network transport over our existing protocol.
First I was just redirecting IO using simply pipe2(), fork(), dup2(), and execve(). This didn't give me a tty on the remote side, so screen, etc. didn't work.
Now I'm using forkpty, and screen mostly works, but many many other don't (vi, stty, etc). It appears the current problem is that the child process doesn't control the tty.
I've been experimenting with TIOCSCTTY, but haven't had much luck.
Here's more or less what I've got:
bool ExternalProcess::launch(...)
{
...
winsize winSize;
winSize.ws_col = 80;
winSize.ws_row = 25;
winSize.ws_xpixel = 10;
winSize.ws_ypixel = 10;
_pid = forkpty(&_stdin, NULL, NULL, &winSize);
//ioctl(_stdin, TIOCNOTTY, NULL);
if (!_pid && (_pid != -1))
{
// this is the child process
char tty[4096];
strncpy(tty, ttyname(STDIN_FILENO), sizeof(tty));
tty[sizeof(tty)-1]=0;
FILE* fp = fopen("debug.txt", "wt"); // no error checking - temporary test code
fprintf(fp, "slave TTY %s", tty);
//if (ioctl(_stdin, TIOCSCTTY, NULL) < 0)
if (ioctl(STDIN_FILENO, TIOCSCTTY, NULL) < 0)
{
fprintf(fp, "ioctl() TIOCSCTTY %s\n", strerror(errno));
fflush(fp);
}
else
{
fprintf(fp, "SET CONTROLLING TTY!");
fflush(fp);
}
fclose(fp);
// command, args, env populated elsewhere
execve(command, args, env);
...
// fail path
_exit(-1);
return false;
}
_stdout = _stdin;
...
// enter select() loop reading/writing _stdin, _stdout
}
I am getting results in the debug file like:
slave TTY /dev/pts/5
SET CONTROLLING TTY!
but still many apps are failing with tcsetattr() errors. Am I right in thinking this is a controlling tty problem? How do I fix it?
EDIT
Minor correction. When I do the ioctl TIOCSCTTY on STDIN_FILENO, then it works as in the debug file above, but the IO redirection back to the parent process is disrupted.
EDIT 2
Okay, I'm starting to understand this better. Looking at the kernel source for the ioctl behind tcsetattr(), the processes I am calling are being sent SIGTTIN and SIGTTOU when trying to change the tty.
Only a foreground process can do that, and they're running as if they're background processes. I tried setting those signals to SIG_IGN after forking and before the execve(), but that didn't work. The semantics of this I understand, but it's safe in my redirection scenario for the execve()'d processes to act as if they're foreground processes. The question is... how to make it so? I will continue to search in the kernel code for clues.
Ugh! It's bash, the shell I was calling with execve().
If it detects that stderr is not attached to a tty, then it enters this special mode where child processes cause SIGTTOU.
I found a mention of this problem here.
When I stopped redirecting stderr away from the tty, then it now seems to work as planned.

Detecting Linux boot with perl and serial device

I am writing a perl script that boots a linux image and needs to detect if the image reached the login prompt. i am using the Device::serial module to communicate with the development board. i am running into problems detecting the login string. i think it might be related to the large amount of prints that occur during a linux boot. the code below tries to capture the prompt. strange enought it only works when i add the unnecessaty "read" command
# Wait for login prompt
$port->are_match("login:");
$gotit = "";
$timeout = 60;
until (($gotit ne "") or ($timeout eq 0))
{
$gotit = $port->lookfor; # poll until data ready
die "Aborted without match\n" unless (defined $gotit);
$read = $port->read(1000000);
$port->lookclear;
sleep(1);
$timeout--;
}
is "lookfor" good for the linux boot scenario at all? why does the "read" make this code work ?
thanks everyone
The CPAN doc page says to do this:
my $gotit = "";
until ("" ne $gotit) {
$gotit = $PortObj->lookfor; # poll until data ready
die "Aborted without match\n" unless (defined $gotit);
sleep 1; # polling sample time
}
There is no call to $port->lookClear in their loop. I suspect this is contributing to your issue. Also be careful with that timeout.

issue with fork() from a firebreath npapi plugin

I am trying to fork() a new process so that I can call a separate console application.
The fork does happen fine and I get a new process id but the process is in sleeping state and does not get active at all even if the browser exits.
I just took the sample plugin project and modified the echo method to do the fork.
A regular console application works fine with the fork code.
Is there something different that has to be taken into account for a firebreath plugin app?
Can someone suggest what might be the issue?
The platform is archlinux 64 bit.
FB::variant PluginTestVZAPI::echo(const FB::variant& msg)
{
static int n(0);
fire_echo("So far, you clicked this many times: ", n++);
// fork
pid_t pid = fork();
if(pid == 0) // Child
{
m_host->htmlLog("child process");
}
else if (pid < 0) // Failed to fork
{
m_host->htmlLog("Failed to fork");
m_host->htmlLog(boost::lexical_cast<std::string>(pid));
}
else // Parent
{
m_host->htmlLog("Parent process");
}
m_host->htmlLog("Child Process PID = " + boost::lexical_cast<std::string>(pid));
// end fork
// return "foobar";
return msg;
}
I can't be certain but if I were you I'd try removing the htmlLog calls -- there is no way for you to access the DOM from the child process, so htmlLog won't work at all and it is quite possible that trying to use it in a forked process is causing it to go into an inactive state while it tries (unsuccessfully) to communicate with a browser process that doesn't know about it.
I don't know for certain if this can work or not, but I'd be more than a bit nervous about forking a process that is already a child process of something else; the browser owns the plugin process and communicates with it via IPC, so if you fork that process there could be a lot of code that you don't know about still running and trying to talk to the browser through a now-defunct IPC connection.
My recommendation would be to launch a seperate process, but that's just me. At the very least, you absolutely cannot use anything FireBreath provides for communicating with the browser from the child process.

after calling exec

After calling exec, is it possible to print a message, because I tried and nothing happened. I read some articles about exec but I couldn't find my answer. It replaces the process image with a new one but not creating a new process. Is it something about it? Does it wait for something I mean if I use it in child process, so does it wait for ending child process?
I can give this example:
char *args[6] = { "cat","-b","-t","-v",argv[1],0};
else if(pid == 0){
printf("Child Process ID:%d, Parent ID:%d, Process
Group:%d\n",getpid(),getppid(),getgid());
execv("/bin/cat",args);
printf("AHMET TANAKOL\n");
}
The exec family, like you already read, replaces the process image. That is, it loads the new program, removes your program, and start running the new program in place of your program.
No call to exec functions ever returns, unless there is an error.

Resources