How do command line clipboard tools like “xclip” and “xsel” persist the clipboard – in a X windows environment that doesn’t

clipboardx-server

After reading this question about the X clipboard getting cleared when vim is exited I learned that the X window clipboard only exists while the program – from which the selection was obtained – remains open.
It is because of this behaviour that programs like "glipper" and "parcellite" exist.

If the X clipboard is cleared every time a program is exited, how do programs like xclip and xsel work?
And what are the security implications of using programs like this? For example, if a password was copied to the clipboard, could this password be saved into some temp file that could be accessed by programs or users?

Best Answer

Unless there's a clipboard application like xclipboard, clipit... that steals the selections from them, xsel/xclip will fork a background process to handle the future selection requests as long as they own the selection.

$ printf test | xclip
$ ps -C xclip
  PID TTY          TIME CMD
14115 pts/10   00:00:00 xclip

That xclip process is handling requests for the selection (here PRIMARY selection). But, if you select something in another application (or use xsel or xclip again to store something else), then that xclip process will concede the selection to that other application and terminate.

$ printf test | xsel
$ ps -C xclip
  PID TTY          TIME CMD
$ ps -C xsel
  PID TTY          TIME CMD
14212 ?        00:00:00 xsel

Above, xsel took over the selection from xclip.

You can find out who owns a given selection with:

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
int main(int argc, char* argv[])
{
    Display *d = XOpenDisplay(NULL);
    Window w = XGetSelectionOwner(d, XInternAtom (d, argv[1], False));
    printf("0x%08x\n", w);
    return 0;
}

Then:

$ make xgo LDFLAGS=-lX11
$ ./xgo PRIMARY
0x07000001

That will give you the window ID. You can use xprop -id or xwininfo -id on that id, but in the case of xclip/xsel, you won't get much information.

On GNU/Linux based systems, ltrace is useful to see what's happening at the X library API level.

See also Capture the X11 protocol's traffic to see what's happening at the X11 protocol level.

Related Question