job control in cygwin bash
Mark Geisert
mark@maxrnd.com
Wed Oct 8 05:54:23 GMT 2025
Hi Vadym,
On 10/7/2025 4:38 AM, Vadym Krevs via Cygwin wrote:
> Hi.
>> I've a question regarding job control in cygwin bash.
>> Below is a simple program that prints out the process id of itself.
>> C:\builds>cat a.c
> #include <stdio.h>
> #include <process.h>
>> int main(int argc, char ** argv)
> {
> printf("pid=%d\n", _getpid());
> return 0;
> }
>> Compiling and running it in foreground from cygwin bash works as expected:
>> user@host /cygdrive/c/builds
> $ cl a.c
> Microsoft (R) C/C++ Optimizing Compiler Version 19.44.35217 for x86
> Copyright (C) Microsoft Corporation. All rights reserved.
>> a.c
> Microsoft (R) Incremental Linker Version 14.44.35217.0
> Copyright (C) Microsoft Corporation. All rights reserved.
>> /out:a.exe
> a.obj
>> user@host /cygdrive/c/builds
> $ ./a
> pid=2352
>>> However, if I start it in background and attempt to get back the pid
> of the started process via $!, the result is not what one would
> expect. The actual process pid printed out from my program differs
> from what cygwin bash thinks is "process ID of the job most recently
> placed into the background".
>> user@host /cygdrive/c/builds
> $ ./a &
> [1] 15909
>> user@host /cygdrive/c/builds
> $ pid=27008
> echo $!
> 15909
> [1]+ Done ./a
>>> So my question is - is this a cygwin bash quirk (i.e. the fact that $!
> is not the pid of the started process) caused by how fork/process
> startup is implemented in cygwin? I have tried reading
> https://cygwin.com/cygwin-ug-net/highlights.html#ov-hi-process but
> could not see anything relevant aside from "Job control works as
> expected in shells that support it." in the Signals section. Is there
> any way to get the actual process pid?
You are using cl to create the executable, and doing so means it results
in a native Windows program, not a Cygwin program. Running ldd.exe on
your executable will show the Cygwin DLL is not associated.
If you instead use gcc to create the executable, this testcase works
correctly. Try 'gcc a.c', assuming you have gcc installed (via Cygwin
Setup Program). You will also have to change "<process.h>" to
"<unistd.h" and "_getpid" to "getpid" in your source file first.
HTH,
..mark
More information about the Cygwin
mailing list