* process.c (Fnetwork_interface_info): Fix pointer signedness.
[bpt/emacs.git] / src / process.c
1 /* Asynchronous subprocess control for GNU Emacs.
2
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2011
4 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 #include <config.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <setjmp.h>
27 #include <sys/types.h> /* some typedefs are used in sys/file.h */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <setjmp.h>
31 #ifdef HAVE_INTTYPES_H
32 #include <inttypes.h>
33 #endif
34
35 #include <unistd.h>
36 #include <fcntl.h>
37
38 /* Only MS-DOS does not define `subprocesses'. */
39 #ifdef subprocesses
40
41 #include <sys/socket.h>
42 #include <netdb.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45
46 /* Are local (unix) sockets supported? */
47 #if defined (HAVE_SYS_UN_H)
48 #if !defined (AF_LOCAL) && defined (AF_UNIX)
49 #define AF_LOCAL AF_UNIX
50 #endif
51 #ifdef AF_LOCAL
52 #define HAVE_LOCAL_SOCKETS
53 #include <sys/un.h>
54 #endif
55 #endif
56
57 #include <sys/ioctl.h>
58 #if defined(HAVE_NET_IF_H)
59 #include <net/if.h>
60 #endif /* HAVE_NET_IF_H */
61
62 #ifdef NEED_BSDTTY
63 #include <bsdtty.h>
64 #endif
65
66 #ifdef HAVE_RES_INIT
67 #include <netinet/in.h>
68 #include <arpa/nameser.h>
69 #include <resolv.h>
70 #endif
71
72 #ifdef HAVE_UTIL_H
73 #include <util.h>
74 #endif
75
76 #ifdef HAVE_PTY_H
77 #include <pty.h>
78 #endif
79
80 #endif /* subprocesses */
81
82 #include "lisp.h"
83 #include "systime.h"
84 #include "systty.h"
85
86 #include "window.h"
87 #include "buffer.h"
88 #include "character.h"
89 #include "coding.h"
90 #include "process.h"
91 #include "frame.h"
92 #include "termhooks.h"
93 #include "termopts.h"
94 #include "commands.h"
95 #include "keyboard.h"
96 #include "blockinput.h"
97 #include "dispextern.h"
98 #include "composite.h"
99 #include "atimer.h"
100 #include "sysselect.h"
101 #include "syssignal.h"
102 #include "syswait.h"
103 #ifdef HAVE_GNUTLS
104 #include "gnutls.h"
105 #endif
106
107 #if defined (USE_GTK) || defined (HAVE_GCONF)
108 #include "xgselect.h"
109 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
110 #ifdef HAVE_NS
111 #include "nsterm.h"
112 #endif
113
114 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
115 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
116 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
117 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
118 Lisp_Object QCname, QCtype;
119 \f
120 /* Non-zero if keyboard input is on hold, zero otherwise. */
121
122 static int kbd_is_on_hold;
123
124 /* Nonzero means don't run process sentinels. This is used
125 when exiting. */
126 int inhibit_sentinels;
127
128 #ifdef subprocesses
129
130 Lisp_Object Qprocessp;
131 Lisp_Object Qrun, Qstop, Qsignal;
132 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
133 Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
134 Lisp_Object Qreal, Qnetwork, Qserial;
135 #ifdef AF_INET6
136 Lisp_Object Qipv6;
137 #endif
138 Lisp_Object QCport, QCspeed, QCprocess;
139 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
140 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
141 Lisp_Object QCbuffer, QChost, QCservice;
142 Lisp_Object QClocal, QCremote, QCcoding;
143 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
144 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
145 Lisp_Object Qlast_nonmenu_event;
146 /* QCfamily is declared and initialized in xfaces.c,
147 QCfilter in keyboard.c. */
148 extern Lisp_Object QCfamily, QCfilter;
149
150 /* Qexit is declared and initialized in eval.c. */
151
152 /* QCfamily is defined in xfaces.c. */
153 extern Lisp_Object QCfamily;
154 /* QCfilter is defined in keyboard.c. */
155 extern Lisp_Object QCfilter;
156
157 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
158 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
159 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
160 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
161
162 /* Define first descriptor number available for subprocesses. */
163 #define FIRST_PROC_DESC 3
164
165 #ifndef HAVE_H_ERRNO
166 extern int h_errno;
167 #endif
168
169 /* These next two vars are non-static since sysdep.c uses them in the
170 emulation of `select'. */
171 /* Number of events of change of status of a process. */
172 int process_tick;
173 /* Number of events for which the user or sentinel has been notified. */
174 int update_tick;
175
176 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
177
178 /* Only W32 has this, it really means that select can't take write mask. */
179 #ifdef BROKEN_NON_BLOCKING_CONNECT
180 #undef NON_BLOCKING_CONNECT
181 #define SELECT_CANT_DO_WRITE_MASK
182 #else
183 #ifndef NON_BLOCKING_CONNECT
184 #ifdef HAVE_SELECT
185 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
186 #if defined (O_NONBLOCK) || defined (O_NDELAY)
187 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
188 #define NON_BLOCKING_CONNECT
189 #endif /* EWOULDBLOCK || EINPROGRESS */
190 #endif /* O_NONBLOCK || O_NDELAY */
191 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
192 #endif /* HAVE_SELECT */
193 #endif /* NON_BLOCKING_CONNECT */
194 #endif /* BROKEN_NON_BLOCKING_CONNECT */
195
196 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
197 this system. We need to read full packets, so we need a
198 "non-destructive" select. So we require either native select,
199 or emulation of select using FIONREAD. */
200
201 #ifdef BROKEN_DATAGRAM_SOCKETS
202 #undef DATAGRAM_SOCKETS
203 #else
204 #ifndef DATAGRAM_SOCKETS
205 #if defined (HAVE_SELECT) || defined (FIONREAD)
206 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
207 #define DATAGRAM_SOCKETS
208 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
209 #endif /* HAVE_SELECT || FIONREAD */
210 #endif /* DATAGRAM_SOCKETS */
211 #endif /* BROKEN_DATAGRAM_SOCKETS */
212
213 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
214 # define HAVE_SEQPACKET
215 #endif
216
217 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
218 #ifdef EMACS_HAS_USECS
219 #define ADAPTIVE_READ_BUFFERING
220 #endif
221 #endif
222
223 #ifdef ADAPTIVE_READ_BUFFERING
224 #define READ_OUTPUT_DELAY_INCREMENT 10000
225 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
226 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
227
228 /* Number of processes which have a non-zero read_output_delay,
229 and therefore might be delayed for adaptive read buffering. */
230
231 static int process_output_delay_count;
232
233 /* Non-zero if any process has non-nil read_output_skip. */
234
235 static int process_output_skip;
236
237 #else
238 #define process_output_delay_count 0
239 #endif
240
241 static int keyboard_bit_set (SELECT_TYPE *);
242 static void deactivate_process (Lisp_Object);
243 static void status_notify (struct Lisp_Process *);
244 static int read_process_output (Lisp_Object, int);
245 static void create_pty (Lisp_Object);
246
247 /* If we support a window system, turn on the code to poll periodically
248 to detect C-g. It isn't actually used when doing interrupt input. */
249 #ifdef HAVE_WINDOW_SYSTEM
250 #define POLL_FOR_INPUT
251 #endif
252
253 static Lisp_Object get_process (register Lisp_Object name);
254 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
255
256 /* Mask of bits indicating the descriptors that we wait for input on. */
257
258 static SELECT_TYPE input_wait_mask;
259
260 /* Mask that excludes keyboard input descriptor(s). */
261
262 static SELECT_TYPE non_keyboard_wait_mask;
263
264 /* Mask that excludes process input descriptor(s). */
265
266 static SELECT_TYPE non_process_wait_mask;
267
268 /* Mask for selecting for write. */
269
270 static SELECT_TYPE write_mask;
271
272 #ifdef NON_BLOCKING_CONNECT
273 /* Mask of bits indicating the descriptors that we wait for connect to
274 complete on. Once they complete, they are removed from this mask
275 and added to the input_wait_mask and non_keyboard_wait_mask. */
276
277 static SELECT_TYPE connect_wait_mask;
278
279 /* Number of bits set in connect_wait_mask. */
280 static int num_pending_connects;
281
282 #define IF_NON_BLOCKING_CONNECT(s) s
283 #else /* NON_BLOCKING_CONNECT */
284 #define IF_NON_BLOCKING_CONNECT(s)
285 #endif /* NON_BLOCKING_CONNECT */
286
287 /* The largest descriptor currently in use for a process object. */
288 static int max_process_desc;
289
290 /* The largest descriptor currently in use for input. */
291 static int max_input_desc;
292
293 /* Indexed by descriptor, gives the process (if any) for that descriptor */
294 Lisp_Object chan_process[MAXDESC];
295
296 /* Alist of elements (NAME . PROCESS) */
297 Lisp_Object Vprocess_alist;
298
299 /* Buffered-ahead input char from process, indexed by channel.
300 -1 means empty (no char is buffered).
301 Used on sys V where the only way to tell if there is any
302 output from the process is to read at least one char.
303 Always -1 on systems that support FIONREAD. */
304
305 /* Don't make static; need to access externally. */
306 int proc_buffered_char[MAXDESC];
307
308 /* Table of `struct coding-system' for each process. */
309 static struct coding_system *proc_decode_coding_system[MAXDESC];
310 static struct coding_system *proc_encode_coding_system[MAXDESC];
311
312 #ifdef DATAGRAM_SOCKETS
313 /* Table of `partner address' for datagram sockets. */
314 struct sockaddr_and_len {
315 struct sockaddr *sa;
316 int len;
317 } datagram_address[MAXDESC];
318 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
319 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
320 #else
321 #define DATAGRAM_CHAN_P(chan) (0)
322 #define DATAGRAM_CONN_P(proc) (0)
323 #endif
324
325 /* Maximum number of bytes to send to a pty without an eof. */
326 static int pty_max_bytes;
327
328 \f
329
330 struct fd_callback_data
331 {
332 fd_callback func;
333 void *data;
334 #define FOR_READ 1
335 #define FOR_WRITE 2
336 int condition; /* mask of the defines above. */
337 } fd_callback_info[MAXDESC];
338
339
340 /* Add a file descriptor FD to be monitored for when read is possible.
341 When read is possible, call FUNC with argument DATA. */
342
343 void
344 add_read_fd (int fd, fd_callback func, void *data)
345 {
346 xassert (fd < MAXDESC);
347 add_keyboard_wait_descriptor (fd);
348
349 fd_callback_info[fd].func = func;
350 fd_callback_info[fd].data = data;
351 fd_callback_info[fd].condition |= FOR_READ;
352 }
353
354 /* Stop monitoring file descriptor FD for when read is possible. */
355
356 void
357 delete_read_fd (int fd)
358 {
359 xassert (fd < MAXDESC);
360 delete_keyboard_wait_descriptor (fd);
361
362 fd_callback_info[fd].condition &= ~FOR_READ;
363 if (fd_callback_info[fd].condition == 0)
364 {
365 fd_callback_info[fd].func = 0;
366 fd_callback_info[fd].data = 0;
367 }
368 }
369
370 /* Add a file descriptor FD to be monitored for when write is possible.
371 When write is possible, call FUNC with argument DATA. */
372
373 void
374 add_write_fd (int fd, fd_callback func, void *data)
375 {
376 xassert (fd < MAXDESC);
377 FD_SET (fd, &write_mask);
378 if (fd > max_input_desc)
379 max_input_desc = fd;
380
381 fd_callback_info[fd].func = func;
382 fd_callback_info[fd].data = data;
383 fd_callback_info[fd].condition |= FOR_WRITE;
384 }
385
386 /* Stop monitoring file descriptor FD for when write is possible. */
387
388 void
389 delete_write_fd (int fd)
390 {
391 int lim = max_input_desc;
392
393 xassert (fd < MAXDESC);
394 FD_CLR (fd, &write_mask);
395 fd_callback_info[fd].condition &= ~FOR_WRITE;
396 if (fd_callback_info[fd].condition == 0)
397 {
398 fd_callback_info[fd].func = 0;
399 fd_callback_info[fd].data = 0;
400
401 if (fd == max_input_desc)
402 for (fd = lim; fd >= 0; fd--)
403 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
404 {
405 max_input_desc = fd;
406 break;
407 }
408
409 }
410 }
411
412 \f
413 /* Compute the Lisp form of the process status, p->status, from
414 the numeric status that was returned by `wait'. */
415
416 static Lisp_Object status_convert (int);
417
418 static void
419 update_status (struct Lisp_Process *p)
420 {
421 eassert (p->raw_status_new);
422 p->status = status_convert (p->raw_status);
423 p->raw_status_new = 0;
424 }
425
426 /* Convert a process status word in Unix format to
427 the list that we use internally. */
428
429 static Lisp_Object
430 status_convert (int w)
431 {
432 if (WIFSTOPPED (w))
433 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
434 else if (WIFEXITED (w))
435 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
436 WCOREDUMP (w) ? Qt : Qnil));
437 else if (WIFSIGNALED (w))
438 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
439 WCOREDUMP (w) ? Qt : Qnil));
440 else
441 return Qrun;
442 }
443
444 /* Given a status-list, extract the three pieces of information
445 and store them individually through the three pointers. */
446
447 static void
448 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
449 {
450 Lisp_Object tem;
451
452 if (SYMBOLP (l))
453 {
454 *symbol = l;
455 *code = 0;
456 *coredump = 0;
457 }
458 else
459 {
460 *symbol = XCAR (l);
461 tem = XCDR (l);
462 *code = XFASTINT (XCAR (tem));
463 tem = XCDR (tem);
464 *coredump = !NILP (tem);
465 }
466 }
467
468 /* Return a string describing a process status list. */
469
470 static Lisp_Object
471 status_message (struct Lisp_Process *p)
472 {
473 Lisp_Object status = p->status;
474 Lisp_Object symbol;
475 int code, coredump;
476 Lisp_Object string, string2;
477
478 decode_status (status, &symbol, &code, &coredump);
479
480 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
481 {
482 char *signame;
483 synchronize_system_messages_locale ();
484 signame = strsignal (code);
485 if (signame == 0)
486 string = build_string ("unknown");
487 else
488 {
489 int c1, c2;
490
491 string = make_unibyte_string (signame, strlen (signame));
492 if (! NILP (Vlocale_coding_system))
493 string = (code_convert_string_norecord
494 (string, Vlocale_coding_system, 0));
495 c1 = STRING_CHAR (SDATA (string));
496 c2 = downcase (c1);
497 if (c1 != c2)
498 Faset (string, make_number (0), make_number (c2));
499 }
500 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
501 return concat2 (string, string2);
502 }
503 else if (EQ (symbol, Qexit))
504 {
505 if (NETCONN1_P (p))
506 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
507 if (code == 0)
508 return build_string ("finished\n");
509 string = Fnumber_to_string (make_number (code));
510 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
511 return concat3 (build_string ("exited abnormally with code "),
512 string, string2);
513 }
514 else if (EQ (symbol, Qfailed))
515 {
516 string = Fnumber_to_string (make_number (code));
517 string2 = build_string ("\n");
518 return concat3 (build_string ("failed with code "),
519 string, string2);
520 }
521 else
522 return Fcopy_sequence (Fsymbol_name (symbol));
523 }
524 \f
525 #ifdef HAVE_PTYS
526
527 /* The file name of the pty opened by allocate_pty. */
528 static char pty_name[24];
529
530 /* Open an available pty, returning a file descriptor.
531 Return -1 on failure.
532 The file name of the terminal corresponding to the pty
533 is left in the variable pty_name. */
534
535 static int
536 allocate_pty (void)
537 {
538 int fd;
539
540 #ifdef PTY_ITERATION
541 PTY_ITERATION
542 #else
543 register int c, i;
544 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
545 for (i = 0; i < 16; i++)
546 #endif
547 {
548 #ifdef PTY_NAME_SPRINTF
549 PTY_NAME_SPRINTF
550 #else
551 sprintf (pty_name, "/dev/pty%c%x", c, i);
552 #endif /* no PTY_NAME_SPRINTF */
553
554 #ifdef PTY_OPEN
555 PTY_OPEN;
556 #else /* no PTY_OPEN */
557 {
558 { /* Some systems name their pseudoterminals so that there are gaps in
559 the usual sequence - for example, on HP9000/S700 systems, there
560 are no pseudoterminals with names ending in 'f'. So we wait for
561 three failures in a row before deciding that we've reached the
562 end of the ptys. */
563 int failed_count = 0;
564 struct stat stb;
565
566 if (stat (pty_name, &stb) < 0)
567 {
568 failed_count++;
569 if (failed_count >= 3)
570 return -1;
571 }
572 else
573 failed_count = 0;
574 }
575 # ifdef O_NONBLOCK
576 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
577 # else
578 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
579 # endif
580 }
581 #endif /* no PTY_OPEN */
582
583 if (fd >= 0)
584 {
585 /* check to make certain that both sides are available
586 this avoids a nasty yet stupid bug in rlogins */
587 #ifdef PTY_TTY_NAME_SPRINTF
588 PTY_TTY_NAME_SPRINTF
589 #else
590 sprintf (pty_name, "/dev/tty%c%x", c, i);
591 #endif /* no PTY_TTY_NAME_SPRINTF */
592 if (access (pty_name, 6) != 0)
593 {
594 emacs_close (fd);
595 # ifndef __sgi
596 continue;
597 # else
598 return -1;
599 # endif /* __sgi */
600 }
601 setup_pty (fd);
602 return fd;
603 }
604 }
605 return -1;
606 }
607 #endif /* HAVE_PTYS */
608 \f
609 static Lisp_Object
610 make_process (Lisp_Object name)
611 {
612 register Lisp_Object val, tem, name1;
613 register struct Lisp_Process *p;
614 char suffix[10];
615 register int i;
616
617 p = allocate_process ();
618
619 p->infd = -1;
620 p->outfd = -1;
621 p->tick = 0;
622 p->update_tick = 0;
623 p->pid = 0;
624 p->pty_flag = 0;
625 p->raw_status_new = 0;
626 p->status = Qrun;
627 p->mark = Fmake_marker ();
628 p->kill_without_query = 0;
629
630 #ifdef ADAPTIVE_READ_BUFFERING
631 p->adaptive_read_buffering = 0;
632 p->read_output_delay = 0;
633 p->read_output_skip = 0;
634 #endif
635
636 #ifdef HAVE_GNUTLS
637 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
638 p->gnutls_log_level = 0;
639 p->gnutls_p = 0;
640 #endif
641
642 /* If name is already in use, modify it until it is unused. */
643
644 name1 = name;
645 for (i = 1; ; i++)
646 {
647 tem = Fget_process (name1);
648 if (NILP (tem)) break;
649 sprintf (suffix, "<%d>", i);
650 name1 = concat2 (name, build_string (suffix));
651 }
652 name = name1;
653 p->name = name;
654 XSETPROCESS (val, p);
655 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
656 return val;
657 }
658
659 static void
660 remove_process (register Lisp_Object proc)
661 {
662 register Lisp_Object pair;
663
664 pair = Frassq (proc, Vprocess_alist);
665 Vprocess_alist = Fdelq (pair, Vprocess_alist);
666
667 deactivate_process (proc);
668 }
669
670 \f
671 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
672 doc: /* Return t if OBJECT is a process. */)
673 (Lisp_Object object)
674 {
675 return PROCESSP (object) ? Qt : Qnil;
676 }
677
678 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
679 doc: /* Return the process named NAME, or nil if there is none. */)
680 (register Lisp_Object name)
681 {
682 if (PROCESSP (name))
683 return name;
684 CHECK_STRING (name);
685 return Fcdr (Fassoc (name, Vprocess_alist));
686 }
687
688 /* This is how commands for the user decode process arguments. It
689 accepts a process, a process name, a buffer, a buffer name, or nil.
690 Buffers denote the first process in the buffer, and nil denotes the
691 current buffer. */
692
693 static Lisp_Object
694 get_process (register Lisp_Object name)
695 {
696 register Lisp_Object proc, obj;
697 if (STRINGP (name))
698 {
699 obj = Fget_process (name);
700 if (NILP (obj))
701 obj = Fget_buffer (name);
702 if (NILP (obj))
703 error ("Process %s does not exist", SDATA (name));
704 }
705 else if (NILP (name))
706 obj = Fcurrent_buffer ();
707 else
708 obj = name;
709
710 /* Now obj should be either a buffer object or a process object.
711 */
712 if (BUFFERP (obj))
713 {
714 proc = Fget_buffer_process (obj);
715 if (NILP (proc))
716 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
717 }
718 else
719 {
720 CHECK_PROCESS (obj);
721 proc = obj;
722 }
723 return proc;
724 }
725
726
727 #ifdef SIGCHLD
728 /* Fdelete_process promises to immediately forget about the process, but in
729 reality, Emacs needs to remember those processes until they have been
730 treated by sigchld_handler; otherwise this handler would consider the
731 process as being synchronous and say that the synchronous process is
732 dead. */
733 static Lisp_Object deleted_pid_list;
734 #endif
735
736 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
737 doc: /* Delete PROCESS: kill it and forget about it immediately.
738 PROCESS may be a process, a buffer, the name of a process or buffer, or
739 nil, indicating the current buffer's process. */)
740 (register Lisp_Object process)
741 {
742 register struct Lisp_Process *p;
743
744 process = get_process (process);
745 p = XPROCESS (process);
746
747 p->raw_status_new = 0;
748 if (NETCONN1_P (p) || SERIALCONN1_P (p))
749 {
750 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
751 p->tick = ++process_tick;
752 status_notify (p);
753 redisplay_preserve_echo_area (13);
754 }
755 else if (p->infd >= 0)
756 {
757 #ifdef SIGCHLD
758 Lisp_Object symbol;
759 /* Assignment to EMACS_INT stops GCC whining about limited range
760 of data type. */
761 EMACS_INT pid = p->pid;
762
763 /* No problem storing the pid here, as it is still in Vprocess_alist. */
764 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
765 /* GC treated elements set to nil. */
766 Fdelq (Qnil, deleted_pid_list));
767 /* If the process has already signaled, remove it from the list. */
768 if (p->raw_status_new)
769 update_status (p);
770 symbol = p->status;
771 if (CONSP (p->status))
772 symbol = XCAR (p->status);
773 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
774 deleted_pid_list
775 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
776 else
777 #endif
778 {
779 Fkill_process (process, Qnil);
780 /* Do this now, since remove_process will make sigchld_handler do nothing. */
781 p->status
782 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
783 p->tick = ++process_tick;
784 status_notify (p);
785 redisplay_preserve_echo_area (13);
786 }
787 }
788 remove_process (process);
789 return Qnil;
790 }
791 \f
792 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
793 doc: /* Return the status of PROCESS.
794 The returned value is one of the following symbols:
795 run -- for a process that is running.
796 stop -- for a process stopped but continuable.
797 exit -- for a process that has exited.
798 signal -- for a process that has got a fatal signal.
799 open -- for a network stream connection that is open.
800 listen -- for a network stream server that is listening.
801 closed -- for a network stream connection that is closed.
802 connect -- when waiting for a non-blocking connection to complete.
803 failed -- when a non-blocking connection has failed.
804 nil -- if arg is a process name and no such process exists.
805 PROCESS may be a process, a buffer, the name of a process, or
806 nil, indicating the current buffer's process. */)
807 (register Lisp_Object process)
808 {
809 register struct Lisp_Process *p;
810 register Lisp_Object status;
811
812 if (STRINGP (process))
813 process = Fget_process (process);
814 else
815 process = get_process (process);
816
817 if (NILP (process))
818 return process;
819
820 p = XPROCESS (process);
821 if (p->raw_status_new)
822 update_status (p);
823 status = p->status;
824 if (CONSP (status))
825 status = XCAR (status);
826 if (NETCONN1_P (p) || SERIALCONN1_P (p))
827 {
828 if (EQ (status, Qexit))
829 status = Qclosed;
830 else if (EQ (p->command, Qt))
831 status = Qstop;
832 else if (EQ (status, Qrun))
833 status = Qopen;
834 }
835 return status;
836 }
837
838 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
839 1, 1, 0,
840 doc: /* Return the exit status of PROCESS or the signal number that killed it.
841 If PROCESS has not yet exited or died, return 0. */)
842 (register Lisp_Object process)
843 {
844 CHECK_PROCESS (process);
845 if (XPROCESS (process)->raw_status_new)
846 update_status (XPROCESS (process));
847 if (CONSP (XPROCESS (process)->status))
848 return XCAR (XCDR (XPROCESS (process)->status));
849 return make_number (0);
850 }
851
852 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
853 doc: /* Return the process id of PROCESS.
854 This is the pid of the external process which PROCESS uses or talks to.
855 For a network connection, this value is nil. */)
856 (register Lisp_Object process)
857 {
858 /* Assignment to EMACS_INT stops GCC whining about limited range of
859 data type. */
860 EMACS_INT pid;
861
862 CHECK_PROCESS (process);
863 pid = XPROCESS (process)->pid;
864 return (pid ? make_fixnum_or_float (pid) : Qnil);
865 }
866
867 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
868 doc: /* Return the name of PROCESS, as a string.
869 This is the name of the program invoked in PROCESS,
870 possibly modified to make it unique among process names. */)
871 (register Lisp_Object process)
872 {
873 CHECK_PROCESS (process);
874 return XPROCESS (process)->name;
875 }
876
877 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
878 doc: /* Return the command that was executed to start PROCESS.
879 This is a list of strings, the first string being the program executed
880 and the rest of the strings being the arguments given to it.
881 For a network or serial process, this is nil (process is running) or t
882 \(process is stopped). */)
883 (register Lisp_Object process)
884 {
885 CHECK_PROCESS (process);
886 return XPROCESS (process)->command;
887 }
888
889 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
890 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
891 This is the terminal that the process itself reads and writes on,
892 not the name of the pty that Emacs uses to talk with that terminal. */)
893 (register Lisp_Object process)
894 {
895 CHECK_PROCESS (process);
896 return XPROCESS (process)->tty_name;
897 }
898
899 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
900 2, 2, 0,
901 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
902 (register Lisp_Object process, Lisp_Object buffer)
903 {
904 struct Lisp_Process *p;
905
906 CHECK_PROCESS (process);
907 if (!NILP (buffer))
908 CHECK_BUFFER (buffer);
909 p = XPROCESS (process);
910 p->buffer = buffer;
911 if (NETCONN1_P (p) || SERIALCONN1_P (p))
912 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
913 setup_process_coding_systems (process);
914 return buffer;
915 }
916
917 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
918 1, 1, 0,
919 doc: /* Return the buffer PROCESS is associated with.
920 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
921 (register Lisp_Object process)
922 {
923 CHECK_PROCESS (process);
924 return XPROCESS (process)->buffer;
925 }
926
927 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
928 1, 1, 0,
929 doc: /* Return the marker for the end of the last output from PROCESS. */)
930 (register Lisp_Object process)
931 {
932 CHECK_PROCESS (process);
933 return XPROCESS (process)->mark;
934 }
935
936 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
937 2, 2, 0,
938 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
939 A value of t means stop accepting output from the process.
940
941 When a process has a filter, its buffer is not used for output.
942 Instead, each time it does output, the entire string of output is
943 passed to the filter.
944
945 The filter gets two arguments: the process and the string of output.
946 The string argument is normally a multibyte string, except:
947 - if the process' input coding system is no-conversion or raw-text,
948 it is a unibyte string (the non-converted input), or else
949 - if `default-enable-multibyte-characters' is nil, it is a unibyte
950 string (the result of converting the decoded input multibyte
951 string to unibyte with `string-make-unibyte'). */)
952 (register Lisp_Object process, Lisp_Object filter)
953 {
954 struct Lisp_Process *p;
955
956 CHECK_PROCESS (process);
957 p = XPROCESS (process);
958
959 /* Don't signal an error if the process' input file descriptor
960 is closed. This could make debugging Lisp more difficult,
961 for example when doing something like
962
963 (setq process (start-process ...))
964 (debug)
965 (set-process-filter process ...) */
966
967 if (p->infd >= 0)
968 {
969 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
970 {
971 FD_CLR (p->infd, &input_wait_mask);
972 FD_CLR (p->infd, &non_keyboard_wait_mask);
973 }
974 else if (EQ (p->filter, Qt)
975 /* Network or serial process not stopped: */
976 && !EQ (p->command, Qt))
977 {
978 FD_SET (p->infd, &input_wait_mask);
979 FD_SET (p->infd, &non_keyboard_wait_mask);
980 }
981 }
982
983 p->filter = filter;
984 if (NETCONN1_P (p) || SERIALCONN1_P (p))
985 p->childp = Fplist_put (p->childp, QCfilter, filter);
986 setup_process_coding_systems (process);
987 return filter;
988 }
989
990 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
991 1, 1, 0,
992 doc: /* Returns the filter function of PROCESS; nil if none.
993 See `set-process-filter' for more info on filter functions. */)
994 (register Lisp_Object process)
995 {
996 CHECK_PROCESS (process);
997 return XPROCESS (process)->filter;
998 }
999
1000 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1001 2, 2, 0,
1002 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1003 The sentinel is called as a function when the process changes state.
1004 It gets two arguments: the process, and a string describing the change. */)
1005 (register Lisp_Object process, Lisp_Object sentinel)
1006 {
1007 struct Lisp_Process *p;
1008
1009 CHECK_PROCESS (process);
1010 p = XPROCESS (process);
1011
1012 p->sentinel = sentinel;
1013 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1014 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1015 return sentinel;
1016 }
1017
1018 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1019 1, 1, 0,
1020 doc: /* Return the sentinel of PROCESS; nil if none.
1021 See `set-process-sentinel' for more info on sentinels. */)
1022 (register Lisp_Object process)
1023 {
1024 CHECK_PROCESS (process);
1025 return XPROCESS (process)->sentinel;
1026 }
1027
1028 DEFUN ("set-process-window-size", Fset_process_window_size,
1029 Sset_process_window_size, 3, 3, 0,
1030 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1031 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1032 {
1033 CHECK_PROCESS (process);
1034 CHECK_NATNUM (height);
1035 CHECK_NATNUM (width);
1036
1037 if (XPROCESS (process)->infd < 0
1038 || set_window_size (XPROCESS (process)->infd,
1039 XINT (height), XINT (width)) <= 0)
1040 return Qnil;
1041 else
1042 return Qt;
1043 }
1044
1045 DEFUN ("set-process-inherit-coding-system-flag",
1046 Fset_process_inherit_coding_system_flag,
1047 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1048 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1049 If the second argument FLAG is non-nil, then the variable
1050 `buffer-file-coding-system' of the buffer associated with PROCESS
1051 will be bound to the value of the coding system used to decode
1052 the process output.
1053
1054 This is useful when the coding system specified for the process buffer
1055 leaves either the character code conversion or the end-of-line conversion
1056 unspecified, or if the coding system used to decode the process output
1057 is more appropriate for saving the process buffer.
1058
1059 Binding the variable `inherit-process-coding-system' to non-nil before
1060 starting the process is an alternative way of setting the inherit flag
1061 for the process which will run. */)
1062 (register Lisp_Object process, Lisp_Object flag)
1063 {
1064 CHECK_PROCESS (process);
1065 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1066 return flag;
1067 }
1068
1069 DEFUN ("set-process-query-on-exit-flag",
1070 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1071 2, 2, 0,
1072 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1073 If the second argument FLAG is non-nil, Emacs will query the user before
1074 exiting or killing a buffer if PROCESS is running. */)
1075 (register Lisp_Object process, Lisp_Object flag)
1076 {
1077 CHECK_PROCESS (process);
1078 XPROCESS (process)->kill_without_query = NILP (flag);
1079 return flag;
1080 }
1081
1082 DEFUN ("process-query-on-exit-flag",
1083 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1084 1, 1, 0,
1085 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1086 (register Lisp_Object process)
1087 {
1088 CHECK_PROCESS (process);
1089 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1090 }
1091
1092 #ifdef DATAGRAM_SOCKETS
1093 Lisp_Object Fprocess_datagram_address (Lisp_Object process);
1094 #endif
1095
1096 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1097 1, 2, 0,
1098 doc: /* Return the contact info of PROCESS; t for a real child.
1099 For a network or serial connection, the value depends on the optional
1100 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1101 SERVICE) for a network connection or (PORT SPEED) for a serial
1102 connection. If KEY is t, the complete contact information for the
1103 connection is returned, else the specific value for the keyword KEY is
1104 returned. See `make-network-process' or `make-serial-process' for a
1105 list of keywords. */)
1106 (register Lisp_Object process, Lisp_Object key)
1107 {
1108 Lisp_Object contact;
1109
1110 CHECK_PROCESS (process);
1111 contact = XPROCESS (process)->childp;
1112
1113 #ifdef DATAGRAM_SOCKETS
1114 if (DATAGRAM_CONN_P (process)
1115 && (EQ (key, Qt) || EQ (key, QCremote)))
1116 contact = Fplist_put (contact, QCremote,
1117 Fprocess_datagram_address (process));
1118 #endif
1119
1120 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1121 return contact;
1122 if (NILP (key) && NETCONN_P (process))
1123 return Fcons (Fplist_get (contact, QChost),
1124 Fcons (Fplist_get (contact, QCservice), Qnil));
1125 if (NILP (key) && SERIALCONN_P (process))
1126 return Fcons (Fplist_get (contact, QCport),
1127 Fcons (Fplist_get (contact, QCspeed), Qnil));
1128 return Fplist_get (contact, key);
1129 }
1130
1131 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1132 1, 1, 0,
1133 doc: /* Return the plist of PROCESS. */)
1134 (register Lisp_Object process)
1135 {
1136 CHECK_PROCESS (process);
1137 return XPROCESS (process)->plist;
1138 }
1139
1140 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1141 2, 2, 0,
1142 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1143 (register Lisp_Object process, Lisp_Object plist)
1144 {
1145 CHECK_PROCESS (process);
1146 CHECK_LIST (plist);
1147
1148 XPROCESS (process)->plist = plist;
1149 return plist;
1150 }
1151
1152 #if 0 /* Turned off because we don't currently record this info
1153 in the process. Perhaps add it. */
1154 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1155 doc: /* Return the connection type of PROCESS.
1156 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1157 a socket connection. */)
1158 (Lisp_Object process)
1159 {
1160 return XPROCESS (process)->type;
1161 }
1162 #endif
1163
1164 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1165 doc: /* Return the connection type of PROCESS.
1166 The value is either the symbol `real', `network', or `serial'.
1167 PROCESS may be a process, a buffer, the name of a process or buffer, or
1168 nil, indicating the current buffer's process. */)
1169 (Lisp_Object process)
1170 {
1171 Lisp_Object proc;
1172 proc = get_process (process);
1173 return XPROCESS (proc)->type;
1174 }
1175
1176 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1177 1, 2, 0,
1178 doc: /* Convert network ADDRESS from internal format to a string.
1179 A 4 or 5 element vector represents an IPv4 address (with port number).
1180 An 8 or 9 element vector represents an IPv6 address (with port number).
1181 If optional second argument OMIT-PORT is non-nil, don't include a port
1182 number in the string, even when present in ADDRESS.
1183 Returns nil if format of ADDRESS is invalid. */)
1184 (Lisp_Object address, Lisp_Object omit_port)
1185 {
1186 if (NILP (address))
1187 return Qnil;
1188
1189 if (STRINGP (address)) /* AF_LOCAL */
1190 return address;
1191
1192 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1193 {
1194 register struct Lisp_Vector *p = XVECTOR (address);
1195 Lisp_Object args[10];
1196 int nargs, i;
1197
1198 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1199 {
1200 args[0] = build_string ("%d.%d.%d.%d");
1201 nargs = 4;
1202 }
1203 else if (p->size == 5)
1204 {
1205 args[0] = build_string ("%d.%d.%d.%d:%d");
1206 nargs = 5;
1207 }
1208 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1209 {
1210 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1211 nargs = 8;
1212 }
1213 else if (p->size == 9)
1214 {
1215 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1216 nargs = 9;
1217 }
1218 else
1219 return Qnil;
1220
1221 for (i = 0; i < nargs; i++)
1222 {
1223 EMACS_INT element = XINT (p->contents[i]);
1224
1225 if (element < 0 || element > 65535)
1226 return Qnil;
1227
1228 if (nargs <= 5 /* IPv4 */
1229 && i < 4 /* host, not port */
1230 && element > 255)
1231 return Qnil;
1232
1233 args[i+1] = p->contents[i];
1234 }
1235
1236 return Fformat (nargs+1, args);
1237 }
1238
1239 if (CONSP (address))
1240 {
1241 Lisp_Object args[2];
1242 args[0] = build_string ("<Family %d>");
1243 args[1] = Fcar (address);
1244 return Fformat (2, args);
1245 }
1246
1247 return Qnil;
1248 }
1249 \f
1250 static Lisp_Object
1251 list_processes_1 (Lisp_Object query_only)
1252 {
1253 register Lisp_Object tail;
1254 Lisp_Object proc, minspace;
1255 register struct Lisp_Process *p;
1256 char tembuf[300];
1257 int w_proc, w_buffer, w_tty;
1258 int exited = 0;
1259 Lisp_Object i_status, i_buffer, i_tty, i_command;
1260
1261 w_proc = 4; /* Proc */
1262 w_buffer = 6; /* Buffer */
1263 w_tty = 0; /* Omit if no ttys */
1264
1265 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1266 {
1267 int i;
1268
1269 proc = Fcdr (XCAR (tail));
1270 p = XPROCESS (proc);
1271 if (NILP (p->type))
1272 continue;
1273 if (!NILP (query_only) && p->kill_without_query)
1274 continue;
1275 if (STRINGP (p->name)
1276 && ( i = SCHARS (p->name), (i > w_proc)))
1277 w_proc = i;
1278 if (!NILP (p->buffer))
1279 {
1280 if (NILP (BVAR (XBUFFER (p->buffer), name)))
1281 {
1282 if (w_buffer < 8)
1283 w_buffer = 8; /* (Killed) */
1284 }
1285 else if ((i = SCHARS (BVAR (XBUFFER (p->buffer), name)), (i > w_buffer)))
1286 w_buffer = i;
1287 }
1288 if (STRINGP (p->tty_name)
1289 && (i = SCHARS (p->tty_name), (i > w_tty)))
1290 w_tty = i;
1291 }
1292
1293 XSETFASTINT (i_status, w_proc + 1);
1294 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1295 if (w_tty)
1296 {
1297 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1298 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1299 }
1300 else
1301 {
1302 i_tty = Qnil;
1303 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1304 }
1305
1306 XSETFASTINT (minspace, 1);
1307
1308 set_buffer_internal (XBUFFER (Vstandard_output));
1309 BVAR (current_buffer, undo_list) = Qt;
1310
1311 BVAR (current_buffer, truncate_lines) = Qt;
1312
1313 write_string ("Proc", -1);
1314 Findent_to (i_status, minspace); write_string ("Status", -1);
1315 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1316 if (!NILP (i_tty))
1317 {
1318 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1319 }
1320 Findent_to (i_command, minspace); write_string ("Command", -1);
1321 write_string ("\n", -1);
1322
1323 write_string ("----", -1);
1324 Findent_to (i_status, minspace); write_string ("------", -1);
1325 Findent_to (i_buffer, minspace); write_string ("------", -1);
1326 if (!NILP (i_tty))
1327 {
1328 Findent_to (i_tty, minspace); write_string ("---", -1);
1329 }
1330 Findent_to (i_command, minspace); write_string ("-------", -1);
1331 write_string ("\n", -1);
1332
1333 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1334 {
1335 Lisp_Object symbol;
1336
1337 proc = Fcdr (XCAR (tail));
1338 p = XPROCESS (proc);
1339 if (NILP (p->type))
1340 continue;
1341 if (!NILP (query_only) && p->kill_without_query)
1342 continue;
1343
1344 Finsert (1, &p->name);
1345 Findent_to (i_status, minspace);
1346
1347 if (p->raw_status_new)
1348 update_status (p);
1349 symbol = p->status;
1350 if (CONSP (p->status))
1351 symbol = XCAR (p->status);
1352
1353 if (EQ (symbol, Qsignal))
1354 {
1355 Lisp_Object tem;
1356 tem = Fcar (Fcdr (p->status));
1357 Fprinc (symbol, Qnil);
1358 }
1359 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1360 {
1361 if (EQ (symbol, Qexit))
1362 write_string ("closed", -1);
1363 else if (EQ (p->command, Qt))
1364 write_string ("stopped", -1);
1365 else if (EQ (symbol, Qrun))
1366 write_string ("open", -1);
1367 else
1368 Fprinc (symbol, Qnil);
1369 }
1370 else if (SERIALCONN1_P (p))
1371 {
1372 write_string ("running", -1);
1373 }
1374 else
1375 Fprinc (symbol, Qnil);
1376
1377 if (EQ (symbol, Qexit))
1378 {
1379 Lisp_Object tem;
1380 tem = Fcar (Fcdr (p->status));
1381 if (XFASTINT (tem))
1382 {
1383 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1384 write_string (tembuf, -1);
1385 }
1386 }
1387
1388 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1389 exited++;
1390
1391 Findent_to (i_buffer, minspace);
1392 if (NILP (p->buffer))
1393 insert_string ("(none)");
1394 else if (NILP (BVAR (XBUFFER (p->buffer), name)))
1395 insert_string ("(Killed)");
1396 else
1397 Finsert (1, &BVAR (XBUFFER (p->buffer), name));
1398
1399 if (!NILP (i_tty))
1400 {
1401 Findent_to (i_tty, minspace);
1402 if (STRINGP (p->tty_name))
1403 Finsert (1, &p->tty_name);
1404 }
1405
1406 Findent_to (i_command, minspace);
1407
1408 if (EQ (p->status, Qlisten))
1409 {
1410 Lisp_Object port = Fplist_get (p->childp, QCservice);
1411 if (INTEGERP (port))
1412 port = Fnumber_to_string (port);
1413 if (NILP (port))
1414 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1415 sprintf (tembuf, "(network %s server on %s)\n",
1416 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1417 (STRINGP (port) ? SSDATA (port) : "?"));
1418 insert_string (tembuf);
1419 }
1420 else if (NETCONN1_P (p))
1421 {
1422 /* For a local socket, there is no host name,
1423 so display service instead. */
1424 Lisp_Object host = Fplist_get (p->childp, QChost);
1425 if (!STRINGP (host))
1426 {
1427 host = Fplist_get (p->childp, QCservice);
1428 if (INTEGERP (host))
1429 host = Fnumber_to_string (host);
1430 }
1431 if (NILP (host))
1432 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1433 sprintf (tembuf, "(network %s connection to %s)\n",
1434 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1435 (STRINGP (host) ? SSDATA (host) : "?"));
1436 insert_string (tembuf);
1437 }
1438 else if (SERIALCONN1_P (p))
1439 {
1440 Lisp_Object port = Fplist_get (p->childp, QCport);
1441 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1442 insert_string ("(serial port ");
1443 if (STRINGP (port))
1444 insert_string (SSDATA (port));
1445 else
1446 insert_string ("?");
1447 if (INTEGERP (speed))
1448 {
1449 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1450 insert_string (tembuf);
1451 }
1452 insert_string (")\n");
1453 }
1454 else
1455 {
1456 Lisp_Object tem = p->command;
1457 while (1)
1458 {
1459 Lisp_Object tem1 = Fcar (tem);
1460 if (NILP (tem1))
1461 break;
1462 Finsert (1, &tem1);
1463 tem = Fcdr (tem);
1464 if (NILP (tem))
1465 break;
1466 insert_string (" ");
1467 }
1468 insert_string ("\n");
1469 }
1470 }
1471 if (exited)
1472 {
1473 status_notify (NULL);
1474 redisplay_preserve_echo_area (13);
1475 }
1476 return Qnil;
1477 }
1478
1479 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1480 doc: /* Display a list of all processes.
1481 If optional argument QUERY-ONLY is non-nil, only processes with
1482 the query-on-exit flag set will be listed.
1483 Any process listed as exited or signaled is actually eliminated
1484 after the listing is made. */)
1485 (Lisp_Object query_only)
1486 {
1487 internal_with_output_to_temp_buffer ("*Process List*",
1488 list_processes_1, query_only);
1489 return Qnil;
1490 }
1491
1492 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1493 doc: /* Return a list of all processes. */)
1494 (void)
1495 {
1496 return Fmapcar (Qcdr, Vprocess_alist);
1497 }
1498 \f
1499 /* Starting asynchronous inferior processes. */
1500
1501 static Lisp_Object start_process_unwind (Lisp_Object proc);
1502
1503 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1504 doc: /* Start a program in a subprocess. Return the process object for it.
1505 NAME is name for process. It is modified if necessary to make it unique.
1506 BUFFER is the buffer (or buffer name) to associate with the process.
1507
1508 Process output (both standard output and standard error streams) goes
1509 at end of BUFFER, unless you specify an output stream or filter
1510 function to handle the output. BUFFER may also be nil, meaning that
1511 this process is not associated with any buffer.
1512
1513 PROGRAM is the program file name. It is searched for in PATH. If
1514 nil, just associate a pty with the buffer. Remaining arguments are
1515 strings to give program as arguments.
1516
1517 If you want to separate standard output from standard error, invoke
1518 the command through a shell and redirect one of them using the shell
1519 syntax.
1520
1521 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1522 (int nargs, register Lisp_Object *args)
1523 {
1524 Lisp_Object buffer, name, program, proc, current_dir, tem;
1525 register unsigned char **new_argv;
1526 register int i;
1527 int count = SPECPDL_INDEX ();
1528
1529 buffer = args[1];
1530 if (!NILP (buffer))
1531 buffer = Fget_buffer_create (buffer);
1532
1533 /* Make sure that the child will be able to chdir to the current
1534 buffer's current directory, or its unhandled equivalent. We
1535 can't just have the child check for an error when it does the
1536 chdir, since it's in a vfork.
1537
1538 We have to GCPRO around this because Fexpand_file_name and
1539 Funhandled_file_name_directory might call a file name handling
1540 function. The argument list is protected by the caller, so all
1541 we really have to worry about is buffer. */
1542 {
1543 struct gcpro gcpro1, gcpro2;
1544
1545 current_dir = BVAR (current_buffer, directory);
1546
1547 GCPRO2 (buffer, current_dir);
1548
1549 current_dir = Funhandled_file_name_directory (current_dir);
1550 if (NILP (current_dir))
1551 /* If the file name handler says that current_dir is unreachable, use
1552 a sensible default. */
1553 current_dir = build_string ("~/");
1554 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1555 if (NILP (Ffile_accessible_directory_p (current_dir)))
1556 report_file_error ("Setting current directory",
1557 Fcons (BVAR (current_buffer, directory), Qnil));
1558
1559 UNGCPRO;
1560 }
1561
1562 name = args[0];
1563 CHECK_STRING (name);
1564
1565 program = args[2];
1566
1567 if (!NILP (program))
1568 CHECK_STRING (program);
1569
1570 proc = make_process (name);
1571 /* If an error occurs and we can't start the process, we want to
1572 remove it from the process list. This means that each error
1573 check in create_process doesn't need to call remove_process
1574 itself; it's all taken care of here. */
1575 record_unwind_protect (start_process_unwind, proc);
1576
1577 XPROCESS (proc)->childp = Qt;
1578 XPROCESS (proc)->plist = Qnil;
1579 XPROCESS (proc)->type = Qreal;
1580 XPROCESS (proc)->buffer = buffer;
1581 XPROCESS (proc)->sentinel = Qnil;
1582 XPROCESS (proc)->filter = Qnil;
1583 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1584
1585 #ifdef HAVE_GNUTLS
1586 /* AKA GNUTLS_INITSTAGE(proc). */
1587 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1588 XPROCESS (proc)->gnutls_cred_type = Qnil;
1589 #endif
1590
1591 #ifdef ADAPTIVE_READ_BUFFERING
1592 XPROCESS (proc)->adaptive_read_buffering
1593 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1594 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1595 #endif
1596
1597 /* Make the process marker point into the process buffer (if any). */
1598 if (BUFFERP (buffer))
1599 set_marker_both (XPROCESS (proc)->mark, buffer,
1600 BUF_ZV (XBUFFER (buffer)),
1601 BUF_ZV_BYTE (XBUFFER (buffer)));
1602
1603 {
1604 /* Decide coding systems for communicating with the process. Here
1605 we don't setup the structure coding_system nor pay attention to
1606 unibyte mode. They are done in create_process. */
1607
1608 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1609 Lisp_Object coding_systems = Qt;
1610 Lisp_Object val, *args2;
1611 struct gcpro gcpro1, gcpro2;
1612
1613 val = Vcoding_system_for_read;
1614 if (NILP (val))
1615 {
1616 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1617 args2[0] = Qstart_process;
1618 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1619 GCPRO2 (proc, current_dir);
1620 if (!NILP (program))
1621 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1622 UNGCPRO;
1623 if (CONSP (coding_systems))
1624 val = XCAR (coding_systems);
1625 else if (CONSP (Vdefault_process_coding_system))
1626 val = XCAR (Vdefault_process_coding_system);
1627 }
1628 XPROCESS (proc)->decode_coding_system = val;
1629
1630 val = Vcoding_system_for_write;
1631 if (NILP (val))
1632 {
1633 if (EQ (coding_systems, Qt))
1634 {
1635 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1636 args2[0] = Qstart_process;
1637 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1638 GCPRO2 (proc, current_dir);
1639 if (!NILP (program))
1640 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1641 UNGCPRO;
1642 }
1643 if (CONSP (coding_systems))
1644 val = XCDR (coding_systems);
1645 else if (CONSP (Vdefault_process_coding_system))
1646 val = XCDR (Vdefault_process_coding_system);
1647 }
1648 XPROCESS (proc)->encode_coding_system = val;
1649 /* Note: At this momemnt, the above coding system may leave
1650 text-conversion or eol-conversion unspecified. They will be
1651 decided after we read output from the process and decode it by
1652 some coding system, or just before we actually send a text to
1653 the process. */
1654 }
1655
1656
1657 XPROCESS (proc)->decoding_buf = empty_unibyte_string;
1658 XPROCESS (proc)->decoding_carryover = 0;
1659 XPROCESS (proc)->encoding_buf = empty_unibyte_string;
1660
1661 XPROCESS (proc)->inherit_coding_system_flag
1662 = !(NILP (buffer) || !inherit_process_coding_system);
1663
1664 if (!NILP (program))
1665 {
1666 /* If program file name is not absolute, search our path for it.
1667 Put the name we will really use in TEM. */
1668 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1669 && !(SCHARS (program) > 1
1670 && IS_DEVICE_SEP (SREF (program, 1))))
1671 {
1672 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1673
1674 tem = Qnil;
1675 GCPRO4 (name, program, buffer, current_dir);
1676 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1677 UNGCPRO;
1678 if (NILP (tem))
1679 report_file_error ("Searching for program", Fcons (program, Qnil));
1680 tem = Fexpand_file_name (tem, Qnil);
1681 }
1682 else
1683 {
1684 if (!NILP (Ffile_directory_p (program)))
1685 error ("Specified program for new process is a directory");
1686 tem = program;
1687 }
1688
1689 /* If program file name starts with /: for quoting a magic name,
1690 discard that. */
1691 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1692 && SREF (tem, 1) == ':')
1693 tem = Fsubstring (tem, make_number (2), Qnil);
1694
1695 {
1696 Lisp_Object arg_encoding = Qnil;
1697 struct gcpro gcpro1;
1698 GCPRO1 (tem);
1699
1700 /* Encode the file name and put it in NEW_ARGV.
1701 That's where the child will use it to execute the program. */
1702 tem = Fcons (ENCODE_FILE (tem), Qnil);
1703
1704 /* Here we encode arguments by the coding system used for sending
1705 data to the process. We don't support using different coding
1706 systems for encoding arguments and for encoding data sent to the
1707 process. */
1708
1709 for (i = 3; i < nargs; i++)
1710 {
1711 tem = Fcons (args[i], tem);
1712 CHECK_STRING (XCAR (tem));
1713 if (STRING_MULTIBYTE (XCAR (tem)))
1714 {
1715 if (NILP (arg_encoding))
1716 arg_encoding = (complement_process_encoding_system
1717 (XPROCESS (proc)->encode_coding_system));
1718 XSETCAR (tem,
1719 code_convert_string_norecord
1720 (XCAR (tem), arg_encoding, 1));
1721 }
1722 }
1723
1724 UNGCPRO;
1725 }
1726
1727 /* Now that everything is encoded we can collect the strings into
1728 NEW_ARGV. */
1729 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1730 new_argv[nargs - 2] = 0;
1731
1732 for (i = nargs - 3; i >= 0; i--)
1733 {
1734 new_argv[i] = SDATA (XCAR (tem));
1735 tem = XCDR (tem);
1736 }
1737
1738 create_process (proc, (char **) new_argv, current_dir);
1739 }
1740 else
1741 create_pty (proc);
1742
1743 return unbind_to (count, proc);
1744 }
1745
1746 /* This function is the unwind_protect form for Fstart_process. If
1747 PROC doesn't have its pid set, then we know someone has signaled
1748 an error and the process wasn't started successfully, so we should
1749 remove it from the process list. */
1750 static Lisp_Object
1751 start_process_unwind (Lisp_Object proc)
1752 {
1753 if (!PROCESSP (proc))
1754 abort ();
1755
1756 /* Was PROC started successfully? */
1757 if (XPROCESS (proc)->pid == -1)
1758 remove_process (proc);
1759
1760 return Qnil;
1761 }
1762
1763 static void
1764 create_process_1 (struct atimer *timer)
1765 {
1766 /* Nothing to do. */
1767 }
1768
1769
1770 void
1771 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1772 {
1773 int inchannel, outchannel;
1774 pid_t pid;
1775 int sv[2];
1776 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1777 int wait_child_setup[2];
1778 #endif
1779 sigset_t procmask;
1780 sigset_t blocked;
1781 struct sigaction sigint_action;
1782 struct sigaction sigquit_action;
1783 struct sigaction sigpipe_action;
1784 #ifdef AIX
1785 struct sigaction sighup_action;
1786 #endif
1787 /* Use volatile to protect variables from being clobbered by longjmp. */
1788 volatile int forkin, forkout;
1789 volatile int pty_flag = 0;
1790 #ifndef USE_CRT_DLL
1791 extern char **environ;
1792 #endif
1793
1794 inchannel = outchannel = -1;
1795
1796 #ifdef HAVE_PTYS
1797 if (!NILP (Vprocess_connection_type))
1798 outchannel = inchannel = allocate_pty ();
1799
1800 if (inchannel >= 0)
1801 {
1802 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1803 /* On most USG systems it does not work to open the pty's tty here,
1804 then close it and reopen it in the child. */
1805 #ifdef O_NOCTTY
1806 /* Don't let this terminal become our controlling terminal
1807 (in case we don't have one). */
1808 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1809 #else
1810 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1811 #endif
1812 if (forkin < 0)
1813 report_file_error ("Opening pty", Qnil);
1814 #else
1815 forkin = forkout = -1;
1816 #endif /* not USG, or USG_SUBTTY_WORKS */
1817 pty_flag = 1;
1818 }
1819 else
1820 #endif /* HAVE_PTYS */
1821 {
1822 int tem;
1823 tem = pipe (sv);
1824 if (tem < 0)
1825 report_file_error ("Creating pipe", Qnil);
1826 inchannel = sv[0];
1827 forkout = sv[1];
1828 tem = pipe (sv);
1829 if (tem < 0)
1830 {
1831 emacs_close (inchannel);
1832 emacs_close (forkout);
1833 report_file_error ("Creating pipe", Qnil);
1834 }
1835 outchannel = sv[1];
1836 forkin = sv[0];
1837 }
1838
1839 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1840 {
1841 int tem;
1842
1843 tem = pipe (wait_child_setup);
1844 if (tem < 0)
1845 report_file_error ("Creating pipe", Qnil);
1846 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1847 if (tem >= 0)
1848 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1849 if (tem < 0)
1850 {
1851 emacs_close (wait_child_setup[0]);
1852 emacs_close (wait_child_setup[1]);
1853 report_file_error ("Setting file descriptor flags", Qnil);
1854 }
1855 }
1856 #endif
1857
1858 #ifdef O_NONBLOCK
1859 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1860 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1861 #else
1862 #ifdef O_NDELAY
1863 fcntl (inchannel, F_SETFL, O_NDELAY);
1864 fcntl (outchannel, F_SETFL, O_NDELAY);
1865 #endif
1866 #endif
1867
1868 /* Record this as an active process, with its channels.
1869 As a result, child_setup will close Emacs's side of the pipes. */
1870 chan_process[inchannel] = process;
1871 XPROCESS (process)->infd = inchannel;
1872 XPROCESS (process)->outfd = outchannel;
1873
1874 /* Previously we recorded the tty descriptor used in the subprocess.
1875 It was only used for getting the foreground tty process, so now
1876 we just reopen the device (see emacs_get_tty_pgrp) as this is
1877 more portable (see USG_SUBTTY_WORKS above). */
1878
1879 XPROCESS (process)->pty_flag = pty_flag;
1880 XPROCESS (process)->status = Qrun;
1881 setup_process_coding_systems (process);
1882
1883 /* Delay interrupts until we have a chance to store
1884 the new fork's pid in its process structure */
1885 sigemptyset (&blocked);
1886 #ifdef SIGCHLD
1887 sigaddset (&blocked, SIGCHLD);
1888 #endif
1889 #ifdef HAVE_WORKING_VFORK
1890 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1891 this sets the parent's signal handlers as well as the child's.
1892 So delay all interrupts whose handlers the child might munge,
1893 and record the current handlers so they can be restored later. */
1894 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1895 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1896 sigaddset (&blocked, SIGPIPE); sigaction (SIGPIPE, 0, &sigpipe_action);
1897 #ifdef AIX
1898 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1899 #endif
1900 #endif /* HAVE_WORKING_VFORK */
1901 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1902
1903 FD_SET (inchannel, &input_wait_mask);
1904 FD_SET (inchannel, &non_keyboard_wait_mask);
1905 if (inchannel > max_process_desc)
1906 max_process_desc = inchannel;
1907
1908 /* Until we store the proper pid, enable sigchld_handler
1909 to recognize an unknown pid as standing for this process.
1910 It is very important not to let this `marker' value stay
1911 in the table after this function has returned; if it does
1912 it might cause call-process to hang and subsequent asynchronous
1913 processes to get their return values scrambled. */
1914 XPROCESS (process)->pid = -1;
1915
1916 BLOCK_INPUT;
1917
1918 {
1919 /* child_setup must clobber environ on systems with true vfork.
1920 Protect it from permanent change. */
1921 char **save_environ = environ;
1922
1923 current_dir = ENCODE_FILE (current_dir);
1924
1925 #ifndef WINDOWSNT
1926 pid = vfork ();
1927 if (pid == 0)
1928 #endif /* not WINDOWSNT */
1929 {
1930 int xforkin = forkin;
1931 int xforkout = forkout;
1932
1933 #if 0 /* This was probably a mistake--it duplicates code later on,
1934 but fails to handle all the cases. */
1935 /* Make sure SIGCHLD is not blocked in the child. */
1936 sigsetmask (SIGEMPTYMASK);
1937 #endif
1938
1939 /* Make the pty be the controlling terminal of the process. */
1940 #ifdef HAVE_PTYS
1941 /* First, disconnect its current controlling terminal. */
1942 #ifdef HAVE_SETSID
1943 /* We tried doing setsid only if pty_flag, but it caused
1944 process_set_signal to fail on SGI when using a pipe. */
1945 setsid ();
1946 /* Make the pty's terminal the controlling terminal. */
1947 if (pty_flag && xforkin >= 0)
1948 {
1949 #ifdef TIOCSCTTY
1950 /* We ignore the return value
1951 because faith@cs.unc.edu says that is necessary on Linux. */
1952 ioctl (xforkin, TIOCSCTTY, 0);
1953 #endif
1954 }
1955 #else /* not HAVE_SETSID */
1956 #ifdef USG
1957 /* It's very important to call setpgrp here and no time
1958 afterwards. Otherwise, we lose our controlling tty which
1959 is set when we open the pty. */
1960 setpgrp ();
1961 #endif /* USG */
1962 #endif /* not HAVE_SETSID */
1963 #if defined (LDISC1)
1964 if (pty_flag && xforkin >= 0)
1965 {
1966 struct termios t;
1967 tcgetattr (xforkin, &t);
1968 t.c_lflag = LDISC1;
1969 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1970 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1971 }
1972 #else
1973 #if defined (NTTYDISC) && defined (TIOCSETD)
1974 if (pty_flag && xforkin >= 0)
1975 {
1976 /* Use new line discipline. */
1977 int ldisc = NTTYDISC;
1978 ioctl (xforkin, TIOCSETD, &ldisc);
1979 }
1980 #endif
1981 #endif
1982 #ifdef TIOCNOTTY
1983 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1984 can do TIOCSPGRP only to the process's controlling tty. */
1985 if (pty_flag)
1986 {
1987 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1988 I can't test it since I don't have 4.3. */
1989 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1990 if (j >= 0)
1991 {
1992 ioctl (j, TIOCNOTTY, 0);
1993 emacs_close (j);
1994 }
1995 #ifndef USG
1996 /* In order to get a controlling terminal on some versions
1997 of BSD, it is necessary to put the process in pgrp 0
1998 before it opens the terminal. */
1999 #ifdef HAVE_SETPGID
2000 setpgid (0, 0);
2001 #else
2002 setpgrp (0, 0);
2003 #endif
2004 #endif
2005 }
2006 #endif /* TIOCNOTTY */
2007
2008 #if !defined (DONT_REOPEN_PTY)
2009 /*** There is a suggestion that this ought to be a
2010 conditional on TIOCSPGRP,
2011 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2012 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2013 that system does seem to need this code, even though
2014 both HAVE_SETSID and TIOCSCTTY are defined. */
2015 /* Now close the pty (if we had it open) and reopen it.
2016 This makes the pty the controlling terminal of the subprocess. */
2017 if (pty_flag)
2018 {
2019
2020 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2021 would work? */
2022 if (xforkin >= 0)
2023 emacs_close (xforkin);
2024 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2025
2026 if (xforkin < 0)
2027 {
2028 emacs_write (1, "Couldn't open the pty terminal ", 31);
2029 emacs_write (1, pty_name, strlen (pty_name));
2030 emacs_write (1, "\n", 1);
2031 _exit (1);
2032 }
2033
2034 }
2035 #endif /* not DONT_REOPEN_PTY */
2036
2037 #ifdef SETUP_SLAVE_PTY
2038 if (pty_flag)
2039 {
2040 SETUP_SLAVE_PTY;
2041 }
2042 #endif /* SETUP_SLAVE_PTY */
2043 #ifdef AIX
2044 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2045 Now reenable it in the child, so it will die when we want it to. */
2046 if (pty_flag)
2047 signal (SIGHUP, SIG_DFL);
2048 #endif
2049 #endif /* HAVE_PTYS */
2050
2051 signal (SIGINT, SIG_DFL);
2052 signal (SIGQUIT, SIG_DFL);
2053 /* GConf causes us to ignore SIGPIPE, make sure it is restored
2054 in the child. */
2055 signal (SIGPIPE, SIG_DFL);
2056
2057 /* Stop blocking signals in the child. */
2058 sigprocmask (SIG_SETMASK, &procmask, 0);
2059
2060 if (pty_flag)
2061 child_setup_tty (xforkout);
2062 #ifdef WINDOWSNT
2063 pid = child_setup (xforkin, xforkout, xforkout,
2064 new_argv, 1, current_dir);
2065 #else /* not WINDOWSNT */
2066 #ifdef FD_CLOEXEC
2067 emacs_close (wait_child_setup[0]);
2068 #endif
2069 child_setup (xforkin, xforkout, xforkout,
2070 new_argv, 1, current_dir);
2071 #endif /* not WINDOWSNT */
2072 }
2073 environ = save_environ;
2074 }
2075
2076 UNBLOCK_INPUT;
2077
2078 /* This runs in the Emacs process. */
2079 if (pid < 0)
2080 {
2081 if (forkin >= 0)
2082 emacs_close (forkin);
2083 if (forkin != forkout && forkout >= 0)
2084 emacs_close (forkout);
2085 }
2086 else
2087 {
2088 /* vfork succeeded. */
2089 XPROCESS (process)->pid = pid;
2090
2091 #ifdef WINDOWSNT
2092 register_child (pid, inchannel);
2093 #endif /* WINDOWSNT */
2094
2095 /* If the subfork execv fails, and it exits,
2096 this close hangs. I don't know why.
2097 So have an interrupt jar it loose. */
2098 {
2099 struct atimer *timer;
2100 EMACS_TIME offset;
2101
2102 stop_polling ();
2103 EMACS_SET_SECS_USECS (offset, 1, 0);
2104 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2105
2106 if (forkin >= 0)
2107 emacs_close (forkin);
2108
2109 cancel_atimer (timer);
2110 start_polling ();
2111 }
2112
2113 if (forkin != forkout && forkout >= 0)
2114 emacs_close (forkout);
2115
2116 #ifdef HAVE_PTYS
2117 if (pty_flag)
2118 XPROCESS (process)->tty_name = build_string (pty_name);
2119 else
2120 #endif
2121 XPROCESS (process)->tty_name = Qnil;
2122
2123 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2124 /* Wait for child_setup to complete in case that vfork is
2125 actually defined as fork. The descriptor wait_child_setup[1]
2126 of a pipe is closed at the child side either by close-on-exec
2127 on successful execvp or the _exit call in child_setup. */
2128 {
2129 char dummy;
2130
2131 emacs_close (wait_child_setup[1]);
2132 emacs_read (wait_child_setup[0], &dummy, 1);
2133 emacs_close (wait_child_setup[0]);
2134 }
2135 #endif
2136 }
2137
2138 /* Restore the signal state whether vfork succeeded or not.
2139 (We will signal an error, below, if it failed.) */
2140 #ifdef HAVE_WORKING_VFORK
2141 /* Restore the parent's signal handlers. */
2142 sigaction (SIGINT, &sigint_action, 0);
2143 sigaction (SIGQUIT, &sigquit_action, 0);
2144 sigaction (SIGPIPE, &sigpipe_action, 0);
2145 #ifdef AIX
2146 sigaction (SIGHUP, &sighup_action, 0);
2147 #endif
2148 #endif /* HAVE_WORKING_VFORK */
2149 /* Stop blocking signals in the parent. */
2150 sigprocmask (SIG_SETMASK, &procmask, 0);
2151
2152 /* Now generate the error if vfork failed. */
2153 if (pid < 0)
2154 report_file_error ("Doing vfork", Qnil);
2155 }
2156
2157 void
2158 create_pty (Lisp_Object process)
2159 {
2160 int inchannel, outchannel;
2161
2162 /* Use volatile to protect variables from being clobbered by longjmp. */
2163 volatile int forkin, forkout;
2164 volatile int pty_flag = 0;
2165
2166 inchannel = outchannel = -1;
2167
2168 #ifdef HAVE_PTYS
2169 if (!NILP (Vprocess_connection_type))
2170 outchannel = inchannel = allocate_pty ();
2171
2172 if (inchannel >= 0)
2173 {
2174 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2175 /* On most USG systems it does not work to open the pty's tty here,
2176 then close it and reopen it in the child. */
2177 #ifdef O_NOCTTY
2178 /* Don't let this terminal become our controlling terminal
2179 (in case we don't have one). */
2180 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2181 #else
2182 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2183 #endif
2184 if (forkin < 0)
2185 report_file_error ("Opening pty", Qnil);
2186 #if defined (DONT_REOPEN_PTY)
2187 /* In the case that vfork is defined as fork, the parent process
2188 (Emacs) may send some data before the child process completes
2189 tty options setup. So we setup tty before forking. */
2190 child_setup_tty (forkout);
2191 #endif /* DONT_REOPEN_PTY */
2192 #else
2193 forkin = forkout = -1;
2194 #endif /* not USG, or USG_SUBTTY_WORKS */
2195 pty_flag = 1;
2196 }
2197 #endif /* HAVE_PTYS */
2198
2199 #ifdef O_NONBLOCK
2200 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2201 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2202 #else
2203 #ifdef O_NDELAY
2204 fcntl (inchannel, F_SETFL, O_NDELAY);
2205 fcntl (outchannel, F_SETFL, O_NDELAY);
2206 #endif
2207 #endif
2208
2209 /* Record this as an active process, with its channels.
2210 As a result, child_setup will close Emacs's side of the pipes. */
2211 chan_process[inchannel] = process;
2212 XPROCESS (process)->infd = inchannel;
2213 XPROCESS (process)->outfd = outchannel;
2214
2215 /* Previously we recorded the tty descriptor used in the subprocess.
2216 It was only used for getting the foreground tty process, so now
2217 we just reopen the device (see emacs_get_tty_pgrp) as this is
2218 more portable (see USG_SUBTTY_WORKS above). */
2219
2220 XPROCESS (process)->pty_flag = pty_flag;
2221 XPROCESS (process)->status = Qrun;
2222 setup_process_coding_systems (process);
2223
2224 FD_SET (inchannel, &input_wait_mask);
2225 FD_SET (inchannel, &non_keyboard_wait_mask);
2226 if (inchannel > max_process_desc)
2227 max_process_desc = inchannel;
2228
2229 XPROCESS (process)->pid = -2;
2230 #ifdef HAVE_PTYS
2231 if (pty_flag)
2232 XPROCESS (process)->tty_name = build_string (pty_name);
2233 else
2234 #endif
2235 XPROCESS (process)->tty_name = Qnil;
2236 }
2237
2238 \f
2239 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2240 The address family of sa is not included in the result. */
2241
2242 static Lisp_Object
2243 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2244 {
2245 Lisp_Object address;
2246 int i;
2247 unsigned char *cp;
2248 register struct Lisp_Vector *p;
2249
2250 /* Workaround for a bug in getsockname on BSD: Names bound to
2251 sockets in the UNIX domain are inaccessible; getsockname returns
2252 a zero length name. */
2253 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2254 return empty_unibyte_string;
2255
2256 switch (sa->sa_family)
2257 {
2258 case AF_INET:
2259 {
2260 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2261 len = sizeof (sin->sin_addr) + 1;
2262 address = Fmake_vector (make_number (len), Qnil);
2263 p = XVECTOR (address);
2264 p->contents[--len] = make_number (ntohs (sin->sin_port));
2265 cp = (unsigned char *) &sin->sin_addr;
2266 break;
2267 }
2268 #ifdef AF_INET6
2269 case AF_INET6:
2270 {
2271 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2272 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2273 len = sizeof (sin6->sin6_addr)/2 + 1;
2274 address = Fmake_vector (make_number (len), Qnil);
2275 p = XVECTOR (address);
2276 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2277 for (i = 0; i < len; i++)
2278 p->contents[i] = make_number (ntohs (ip6[i]));
2279 return address;
2280 }
2281 #endif
2282 #ifdef HAVE_LOCAL_SOCKETS
2283 case AF_LOCAL:
2284 {
2285 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2286 for (i = 0; i < sizeof (sockun->sun_path); i++)
2287 if (sockun->sun_path[i] == 0)
2288 break;
2289 return make_unibyte_string (sockun->sun_path, i);
2290 }
2291 #endif
2292 default:
2293 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2294 address = Fcons (make_number (sa->sa_family),
2295 Fmake_vector (make_number (len), Qnil));
2296 p = XVECTOR (XCDR (address));
2297 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2298 break;
2299 }
2300
2301 i = 0;
2302 while (i < len)
2303 p->contents[i++] = make_number (*cp++);
2304
2305 return address;
2306 }
2307
2308
2309 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2310
2311 static int
2312 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2313 {
2314 register struct Lisp_Vector *p;
2315
2316 if (VECTORP (address))
2317 {
2318 p = XVECTOR (address);
2319 if (p->size == 5)
2320 {
2321 *familyp = AF_INET;
2322 return sizeof (struct sockaddr_in);
2323 }
2324 #ifdef AF_INET6
2325 else if (p->size == 9)
2326 {
2327 *familyp = AF_INET6;
2328 return sizeof (struct sockaddr_in6);
2329 }
2330 #endif
2331 }
2332 #ifdef HAVE_LOCAL_SOCKETS
2333 else if (STRINGP (address))
2334 {
2335 *familyp = AF_LOCAL;
2336 return sizeof (struct sockaddr_un);
2337 }
2338 #endif
2339 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2340 {
2341 struct sockaddr *sa;
2342 *familyp = XINT (XCAR (address));
2343 p = XVECTOR (XCDR (address));
2344 return p->size + sizeof (sa->sa_family);
2345 }
2346 return 0;
2347 }
2348
2349 /* Convert an address object (vector or string) to an internal sockaddr.
2350
2351 The address format has been basically validated by
2352 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2353 it could have come from user data. So if FAMILY is not valid,
2354 we return after zeroing *SA. */
2355
2356 static void
2357 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2358 {
2359 register struct Lisp_Vector *p;
2360 register unsigned char *cp = NULL;
2361 register int i;
2362
2363 memset (sa, 0, len);
2364
2365 if (VECTORP (address))
2366 {
2367 p = XVECTOR (address);
2368 if (family == AF_INET)
2369 {
2370 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2371 len = sizeof (sin->sin_addr) + 1;
2372 i = XINT (p->contents[--len]);
2373 sin->sin_port = htons (i);
2374 cp = (unsigned char *)&sin->sin_addr;
2375 sa->sa_family = family;
2376 }
2377 #ifdef AF_INET6
2378 else if (family == AF_INET6)
2379 {
2380 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2381 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2382 len = sizeof (sin6->sin6_addr) + 1;
2383 i = XINT (p->contents[--len]);
2384 sin6->sin6_port = htons (i);
2385 for (i = 0; i < len; i++)
2386 if (INTEGERP (p->contents[i]))
2387 {
2388 int j = XFASTINT (p->contents[i]) & 0xffff;
2389 ip6[i] = ntohs (j);
2390 }
2391 sa->sa_family = family;
2392 return;
2393 }
2394 #endif
2395 else
2396 return;
2397 }
2398 else if (STRINGP (address))
2399 {
2400 #ifdef HAVE_LOCAL_SOCKETS
2401 if (family == AF_LOCAL)
2402 {
2403 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2404 cp = SDATA (address);
2405 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2406 sockun->sun_path[i] = *cp++;
2407 sa->sa_family = family;
2408 }
2409 #endif
2410 return;
2411 }
2412 else
2413 {
2414 p = XVECTOR (XCDR (address));
2415 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2416 }
2417
2418 for (i = 0; i < len; i++)
2419 if (INTEGERP (p->contents[i]))
2420 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2421 }
2422
2423 #ifdef DATAGRAM_SOCKETS
2424 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2425 1, 1, 0,
2426 doc: /* Get the current datagram address associated with PROCESS. */)
2427 (Lisp_Object process)
2428 {
2429 int channel;
2430
2431 CHECK_PROCESS (process);
2432
2433 if (!DATAGRAM_CONN_P (process))
2434 return Qnil;
2435
2436 channel = XPROCESS (process)->infd;
2437 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2438 datagram_address[channel].len);
2439 }
2440
2441 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2442 2, 2, 0,
2443 doc: /* Set the datagram address for PROCESS to ADDRESS.
2444 Returns nil upon error setting address, ADDRESS otherwise. */)
2445 (Lisp_Object process, Lisp_Object address)
2446 {
2447 int channel;
2448 int family, len;
2449
2450 CHECK_PROCESS (process);
2451
2452 if (!DATAGRAM_CONN_P (process))
2453 return Qnil;
2454
2455 channel = XPROCESS (process)->infd;
2456
2457 len = get_lisp_to_sockaddr_size (address, &family);
2458 if (datagram_address[channel].len != len)
2459 return Qnil;
2460 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2461 return address;
2462 }
2463 #endif
2464 \f
2465
2466 static const struct socket_options {
2467 /* The name of this option. Should be lowercase version of option
2468 name without SO_ prefix. */
2469 const char *name;
2470 /* Option level SOL_... */
2471 int optlevel;
2472 /* Option number SO_... */
2473 int optnum;
2474 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2475 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2476 } socket_options[] =
2477 {
2478 #ifdef SO_BINDTODEVICE
2479 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2480 #endif
2481 #ifdef SO_BROADCAST
2482 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2483 #endif
2484 #ifdef SO_DONTROUTE
2485 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2486 #endif
2487 #ifdef SO_KEEPALIVE
2488 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2489 #endif
2490 #ifdef SO_LINGER
2491 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2492 #endif
2493 #ifdef SO_OOBINLINE
2494 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2495 #endif
2496 #ifdef SO_PRIORITY
2497 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2498 #endif
2499 #ifdef SO_REUSEADDR
2500 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2501 #endif
2502 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2503 };
2504
2505 /* Set option OPT to value VAL on socket S.
2506
2507 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2508 Signals an error if setting a known option fails.
2509 */
2510
2511 static int
2512 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2513 {
2514 char *name;
2515 const struct socket_options *sopt;
2516 int ret = 0;
2517
2518 CHECK_SYMBOL (opt);
2519
2520 name = SSDATA (SYMBOL_NAME (opt));
2521 for (sopt = socket_options; sopt->name; sopt++)
2522 if (strcmp (name, sopt->name) == 0)
2523 break;
2524
2525 switch (sopt->opttype)
2526 {
2527 case SOPT_BOOL:
2528 {
2529 int optval;
2530 optval = NILP (val) ? 0 : 1;
2531 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2532 &optval, sizeof (optval));
2533 break;
2534 }
2535
2536 case SOPT_INT:
2537 {
2538 int optval;
2539 if (INTEGERP (val))
2540 optval = XINT (val);
2541 else
2542 error ("Bad option value for %s", name);
2543 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2544 &optval, sizeof (optval));
2545 break;
2546 }
2547
2548 #ifdef SO_BINDTODEVICE
2549 case SOPT_IFNAME:
2550 {
2551 char devname[IFNAMSIZ+1];
2552
2553 /* This is broken, at least in the Linux 2.4 kernel.
2554 To unbind, the arg must be a zero integer, not the empty string.
2555 This should work on all systems. KFS. 2003-09-23. */
2556 memset (devname, 0, sizeof devname);
2557 if (STRINGP (val))
2558 {
2559 char *arg = SSDATA (val);
2560 int len = min (strlen (arg), IFNAMSIZ);
2561 memcpy (devname, arg, len);
2562 }
2563 else if (!NILP (val))
2564 error ("Bad option value for %s", name);
2565 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2566 devname, IFNAMSIZ);
2567 break;
2568 }
2569 #endif
2570
2571 #ifdef SO_LINGER
2572 case SOPT_LINGER:
2573 {
2574 struct linger linger;
2575
2576 linger.l_onoff = 1;
2577 linger.l_linger = 0;
2578 if (INTEGERP (val))
2579 linger.l_linger = XINT (val);
2580 else
2581 linger.l_onoff = NILP (val) ? 0 : 1;
2582 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2583 &linger, sizeof (linger));
2584 break;
2585 }
2586 #endif
2587
2588 default:
2589 return 0;
2590 }
2591
2592 if (ret < 0)
2593 report_file_error ("Cannot set network option",
2594 Fcons (opt, Fcons (val, Qnil)));
2595 return (1 << sopt->optbit);
2596 }
2597
2598
2599 DEFUN ("set-network-process-option",
2600 Fset_network_process_option, Sset_network_process_option,
2601 3, 4, 0,
2602 doc: /* For network process PROCESS set option OPTION to value VALUE.
2603 See `make-network-process' for a list of options and values.
2604 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2605 OPTION is not a supported option, return nil instead; otherwise return t. */)
2606 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2607 {
2608 int s;
2609 struct Lisp_Process *p;
2610
2611 CHECK_PROCESS (process);
2612 p = XPROCESS (process);
2613 if (!NETCONN1_P (p))
2614 error ("Process is not a network process");
2615
2616 s = p->infd;
2617 if (s < 0)
2618 error ("Process is not running");
2619
2620 if (set_socket_option (s, option, value))
2621 {
2622 p->childp = Fplist_put (p->childp, option, value);
2623 return Qt;
2624 }
2625
2626 if (NILP (no_error))
2627 error ("Unknown or unsupported option");
2628
2629 return Qnil;
2630 }
2631
2632 \f
2633 DEFUN ("serial-process-configure",
2634 Fserial_process_configure,
2635 Sserial_process_configure,
2636 0, MANY, 0,
2637 doc: /* Configure speed, bytesize, etc. of a serial process.
2638
2639 Arguments are specified as keyword/argument pairs. Attributes that
2640 are not given are re-initialized from the process's current
2641 configuration (available via the function `process-contact') or set to
2642 reasonable default values. The following arguments are defined:
2643
2644 :process PROCESS
2645 :name NAME
2646 :buffer BUFFER
2647 :port PORT
2648 -- Any of these arguments can be given to identify the process that is
2649 to be configured. If none of these arguments is given, the current
2650 buffer's process is used.
2651
2652 :speed SPEED -- SPEED is the speed of the serial port in bits per
2653 second, also called baud rate. Any value can be given for SPEED, but
2654 most serial ports work only at a few defined values between 1200 and
2655 115200, with 9600 being the most common value. If SPEED is nil, the
2656 serial port is not configured any further, i.e., all other arguments
2657 are ignored. This may be useful for special serial ports such as
2658 Bluetooth-to-serial converters which can only be configured through AT
2659 commands. A value of nil for SPEED can be used only when passed
2660 through `make-serial-process' or `serial-term'.
2661
2662 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2663 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2664
2665 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2666 `odd' (use odd parity), or the symbol `even' (use even parity). If
2667 PARITY is not given, no parity is used.
2668
2669 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2670 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2671 is not given or nil, 1 stopbit is used.
2672
2673 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2674 flowcontrol to be used, which is either nil (don't use flowcontrol),
2675 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2676 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2677 flowcontrol is used.
2678
2679 `serial-process-configure' is called by `make-serial-process' for the
2680 initial configuration of the serial port.
2681
2682 Examples:
2683
2684 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2685
2686 \(serial-process-configure
2687 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2688
2689 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2690
2691 usage: (serial-process-configure &rest ARGS) */)
2692 (int nargs, Lisp_Object *args)
2693 {
2694 struct Lisp_Process *p;
2695 Lisp_Object contact = Qnil;
2696 Lisp_Object proc = Qnil;
2697 struct gcpro gcpro1;
2698
2699 contact = Flist (nargs, args);
2700 GCPRO1 (contact);
2701
2702 proc = Fplist_get (contact, QCprocess);
2703 if (NILP (proc))
2704 proc = Fplist_get (contact, QCname);
2705 if (NILP (proc))
2706 proc = Fplist_get (contact, QCbuffer);
2707 if (NILP (proc))
2708 proc = Fplist_get (contact, QCport);
2709 proc = get_process (proc);
2710 p = XPROCESS (proc);
2711 if (!EQ (p->type, Qserial))
2712 error ("Not a serial process");
2713
2714 if (NILP (Fplist_get (p->childp, QCspeed)))
2715 {
2716 UNGCPRO;
2717 return Qnil;
2718 }
2719
2720 serial_configure (p, contact);
2721
2722 UNGCPRO;
2723 return Qnil;
2724 }
2725
2726 /* Used by make-serial-process to recover from errors. */
2727 static Lisp_Object
2728 make_serial_process_unwind (Lisp_Object proc)
2729 {
2730 if (!PROCESSP (proc))
2731 abort ();
2732 remove_process (proc);
2733 return Qnil;
2734 }
2735
2736 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2737 0, MANY, 0,
2738 doc: /* Create and return a serial port process.
2739
2740 In Emacs, serial port connections are represented by process objects,
2741 so input and output work as for subprocesses, and `delete-process'
2742 closes a serial port connection. However, a serial process has no
2743 process id, it cannot be signaled, and the status codes are different
2744 from normal processes.
2745
2746 `make-serial-process' creates a process and a buffer, on which you
2747 probably want to use `process-send-string'. Try \\[serial-term] for
2748 an interactive terminal. See below for examples.
2749
2750 Arguments are specified as keyword/argument pairs. The following
2751 arguments are defined:
2752
2753 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2754 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2755 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2756 the backslashes in strings).
2757
2758 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2759 which is called by `make-serial-process'.
2760
2761 :name NAME -- NAME is the name of the process. If NAME is not given,
2762 the value of PORT is used.
2763
2764 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2765 with the process. Process output goes at the end of that buffer,
2766 unless you specify an output stream or filter function to handle the
2767 output. If BUFFER is not given, the value of NAME is used.
2768
2769 :coding CODING -- If CODING is a symbol, it specifies the coding
2770 system used for both reading and writing for this process. If CODING
2771 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2772 ENCODING is used for writing.
2773
2774 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2775 the process is running. If BOOL is not given, query before exiting.
2776
2777 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2778 In the stopped state, a serial process does not accept incoming data,
2779 but you can send outgoing data. The stopped state is cleared by
2780 `continue-process' and set by `stop-process'.
2781
2782 :filter FILTER -- Install FILTER as the process filter.
2783
2784 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2785
2786 :plist PLIST -- Install PLIST as the initial plist of the process.
2787
2788 :speed
2789 :bytesize
2790 :parity
2791 :stopbits
2792 :flowcontrol
2793 -- These arguments are handled by `serial-process-configure', which is
2794 called by `make-serial-process'.
2795
2796 The original argument list, possibly modified by later configuration,
2797 is available via the function `process-contact'.
2798
2799 Examples:
2800
2801 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2802
2803 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2804
2805 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2806
2807 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2808
2809 usage: (make-serial-process &rest ARGS) */)
2810 (int nargs, Lisp_Object *args)
2811 {
2812 int fd = -1;
2813 Lisp_Object proc, contact, port;
2814 struct Lisp_Process *p;
2815 struct gcpro gcpro1;
2816 Lisp_Object name, buffer;
2817 Lisp_Object tem, val;
2818 int specpdl_count = -1;
2819
2820 if (nargs == 0)
2821 return Qnil;
2822
2823 contact = Flist (nargs, args);
2824 GCPRO1 (contact);
2825
2826 port = Fplist_get (contact, QCport);
2827 if (NILP (port))
2828 error ("No port specified");
2829 CHECK_STRING (port);
2830
2831 if (NILP (Fplist_member (contact, QCspeed)))
2832 error (":speed not specified");
2833 if (!NILP (Fplist_get (contact, QCspeed)))
2834 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2835
2836 name = Fplist_get (contact, QCname);
2837 if (NILP (name))
2838 name = port;
2839 CHECK_STRING (name);
2840 proc = make_process (name);
2841 specpdl_count = SPECPDL_INDEX ();
2842 record_unwind_protect (make_serial_process_unwind, proc);
2843 p = XPROCESS (proc);
2844
2845 fd = serial_open (SSDATA (port));
2846 p->infd = fd;
2847 p->outfd = fd;
2848 if (fd > max_process_desc)
2849 max_process_desc = fd;
2850 chan_process[fd] = proc;
2851
2852 buffer = Fplist_get (contact, QCbuffer);
2853 if (NILP (buffer))
2854 buffer = name;
2855 buffer = Fget_buffer_create (buffer);
2856 p->buffer = buffer;
2857
2858 p->childp = contact;
2859 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2860 p->type = Qserial;
2861 p->sentinel = Fplist_get (contact, QCsentinel);
2862 p->filter = Fplist_get (contact, QCfilter);
2863 p->log = Qnil;
2864 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2865 p->kill_without_query = 1;
2866 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2867 p->command = Qt;
2868 p->pty_flag = 0;
2869
2870 if (!EQ (p->command, Qt))
2871 {
2872 FD_SET (fd, &input_wait_mask);
2873 FD_SET (fd, &non_keyboard_wait_mask);
2874 }
2875
2876 if (BUFFERP (buffer))
2877 {
2878 set_marker_both (p->mark, buffer,
2879 BUF_ZV (XBUFFER (buffer)),
2880 BUF_ZV_BYTE (XBUFFER (buffer)));
2881 }
2882
2883 tem = Fplist_member (contact, QCcoding);
2884 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2885 tem = Qnil;
2886
2887 val = Qnil;
2888 if (!NILP (tem))
2889 {
2890 val = XCAR (XCDR (tem));
2891 if (CONSP (val))
2892 val = XCAR (val);
2893 }
2894 else if (!NILP (Vcoding_system_for_read))
2895 val = Vcoding_system_for_read;
2896 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2897 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2898 val = Qnil;
2899 p->decode_coding_system = val;
2900
2901 val = Qnil;
2902 if (!NILP (tem))
2903 {
2904 val = XCAR (XCDR (tem));
2905 if (CONSP (val))
2906 val = XCDR (val);
2907 }
2908 else if (!NILP (Vcoding_system_for_write))
2909 val = Vcoding_system_for_write;
2910 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2911 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2912 val = Qnil;
2913 p->encode_coding_system = val;
2914
2915 setup_process_coding_systems (proc);
2916 p->decoding_buf = empty_unibyte_string;
2917 p->decoding_carryover = 0;
2918 p->encoding_buf = empty_unibyte_string;
2919 p->inherit_coding_system_flag
2920 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2921
2922 Fserial_process_configure (nargs, args);
2923
2924 specpdl_ptr = specpdl + specpdl_count;
2925
2926 UNGCPRO;
2927 return proc;
2928 }
2929
2930 /* Create a network stream/datagram client/server process. Treated
2931 exactly like a normal process when reading and writing. Primary
2932 differences are in status display and process deletion. A network
2933 connection has no PID; you cannot signal it. All you can do is
2934 stop/continue it and deactivate/close it via delete-process */
2935
2936 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2937 0, MANY, 0,
2938 doc: /* Create and return a network server or client process.
2939
2940 In Emacs, network connections are represented by process objects, so
2941 input and output work as for subprocesses and `delete-process' closes
2942 a network connection. However, a network process has no process id,
2943 it cannot be signaled, and the status codes are different from normal
2944 processes.
2945
2946 Arguments are specified as keyword/argument pairs. The following
2947 arguments are defined:
2948
2949 :name NAME -- NAME is name for process. It is modified if necessary
2950 to make it unique.
2951
2952 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2953 with the process. Process output goes at end of that buffer, unless
2954 you specify an output stream or filter function to handle the output.
2955 BUFFER may be also nil, meaning that this process is not associated
2956 with any buffer.
2957
2958 :host HOST -- HOST is name of the host to connect to, or its IP
2959 address. The symbol `local' specifies the local host. If specified
2960 for a server process, it must be a valid name or address for the local
2961 host, and only clients connecting to that address will be accepted.
2962
2963 :service SERVICE -- SERVICE is name of the service desired, or an
2964 integer specifying a port number to connect to. If SERVICE is t,
2965 a random port number is selected for the server. (If Emacs was
2966 compiled with getaddrinfo, a port number can also be specified as a
2967 string, e.g. "80", as well as an integer. This is not portable.)
2968
2969 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2970 stream type connection, `datagram' creates a datagram type connection,
2971 `seqpacket' creates a reliable datagram connection.
2972
2973 :family FAMILY -- FAMILY is the address (and protocol) family for the
2974 service specified by HOST and SERVICE. The default (nil) is to use
2975 whatever address family (IPv4 or IPv6) that is defined for the host
2976 and port number specified by HOST and SERVICE. Other address families
2977 supported are:
2978 local -- for a local (i.e. UNIX) address specified by SERVICE.
2979 ipv4 -- use IPv4 address family only.
2980 ipv6 -- use IPv6 address family only.
2981
2982 :local ADDRESS -- ADDRESS is the local address used for the connection.
2983 This parameter is ignored when opening a client process. When specified
2984 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2985
2986 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2987 connection. This parameter is ignored when opening a stream server
2988 process. For a datagram server process, it specifies the initial
2989 setting of the remote datagram address. When specified for a client
2990 process, the FAMILY, HOST, and SERVICE args are ignored.
2991
2992 The format of ADDRESS depends on the address family:
2993 - An IPv4 address is represented as an vector of integers [A B C D P]
2994 corresponding to numeric IP address A.B.C.D and port number P.
2995 - A local address is represented as a string with the address in the
2996 local address space.
2997 - An "unsupported family" address is represented by a cons (F . AV)
2998 where F is the family number and AV is a vector containing the socket
2999 address data with one element per address data byte. Do not rely on
3000 this format in portable code, as it may depend on implementation
3001 defined constants, data sizes, and data structure alignment.
3002
3003 :coding CODING -- If CODING is a symbol, it specifies the coding
3004 system used for both reading and writing for this process. If CODING
3005 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3006 ENCODING is used for writing.
3007
3008 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3009 return without waiting for the connection to complete; instead, the
3010 sentinel function will be called with second arg matching "open" (if
3011 successful) or "failed" when the connect completes. Default is to use
3012 a blocking connect (i.e. wait) for stream type connections.
3013
3014 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3015 running when Emacs is exited.
3016
3017 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3018 In the stopped state, a server process does not accept new
3019 connections, and a client process does not handle incoming traffic.
3020 The stopped state is cleared by `continue-process' and set by
3021 `stop-process'.
3022
3023 :filter FILTER -- Install FILTER as the process filter.
3024
3025 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3026 process filter are multibyte, otherwise they are unibyte.
3027 If this keyword is not specified, the strings are multibyte if
3028 `default-enable-multibyte-characters' is non-nil.
3029
3030 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3031
3032 :log LOG -- Install LOG as the server process log function. This
3033 function is called when the server accepts a network connection from a
3034 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3035 is the server process, CLIENT is the new process for the connection,
3036 and MESSAGE is a string.
3037
3038 :plist PLIST -- Install PLIST as the new process' initial plist.
3039
3040 :server QLEN -- if QLEN is non-nil, create a server process for the
3041 specified FAMILY, SERVICE, and connection type (stream or datagram).
3042 If QLEN is an integer, it is used as the max. length of the server's
3043 pending connection queue (also known as the backlog); the default
3044 queue length is 5. Default is to create a client process.
3045
3046 The following network options can be specified for this connection:
3047
3048 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3049 :dontroute BOOL -- Only send to directly connected hosts.
3050 :keepalive BOOL -- Send keep-alive messages on network stream.
3051 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3052 :oobinline BOOL -- Place out-of-band data in receive data stream.
3053 :priority INT -- Set protocol defined priority for sent packets.
3054 :reuseaddr BOOL -- Allow reusing a recently used local address
3055 (this is allowed by default for a server process).
3056 :bindtodevice NAME -- bind to interface NAME. Using this may require
3057 special privileges on some systems.
3058
3059 Consult the relevant system programmer's manual pages for more
3060 information on using these options.
3061
3062
3063 A server process will listen for and accept connections from clients.
3064 When a client connection is accepted, a new network process is created
3065 for the connection with the following parameters:
3066
3067 - The client's process name is constructed by concatenating the server
3068 process' NAME and a client identification string.
3069 - If the FILTER argument is non-nil, the client process will not get a
3070 separate process buffer; otherwise, the client's process buffer is a newly
3071 created buffer named after the server process' BUFFER name or process
3072 NAME concatenated with the client identification string.
3073 - The connection type and the process filter and sentinel parameters are
3074 inherited from the server process' TYPE, FILTER and SENTINEL.
3075 - The client process' contact info is set according to the client's
3076 addressing information (typically an IP address and a port number).
3077 - The client process' plist is initialized from the server's plist.
3078
3079 Notice that the FILTER and SENTINEL args are never used directly by
3080 the server process. Also, the BUFFER argument is not used directly by
3081 the server process, but via the optional :log function, accepted (and
3082 failed) connections may be logged in the server process' buffer.
3083
3084 The original argument list, modified with the actual connection
3085 information, is available via the `process-contact' function.
3086
3087 usage: (make-network-process &rest ARGS) */)
3088 (int nargs, Lisp_Object *args)
3089 {
3090 Lisp_Object proc;
3091 Lisp_Object contact;
3092 struct Lisp_Process *p;
3093 #ifdef HAVE_GETADDRINFO
3094 struct addrinfo ai, *res, *lres;
3095 struct addrinfo hints;
3096 const char *portstring;
3097 char portbuf[128];
3098 #else /* HAVE_GETADDRINFO */
3099 struct _emacs_addrinfo
3100 {
3101 int ai_family;
3102 int ai_socktype;
3103 int ai_protocol;
3104 int ai_addrlen;
3105 struct sockaddr *ai_addr;
3106 struct _emacs_addrinfo *ai_next;
3107 } ai, *res, *lres;
3108 #endif /* HAVE_GETADDRINFO */
3109 struct sockaddr_in address_in;
3110 #ifdef HAVE_LOCAL_SOCKETS
3111 struct sockaddr_un address_un;
3112 #endif
3113 int port;
3114 int ret = 0;
3115 int xerrno = 0;
3116 int s = -1, outch, inch;
3117 struct gcpro gcpro1;
3118 int count = SPECPDL_INDEX ();
3119 int count1;
3120 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3121 Lisp_Object tem;
3122 Lisp_Object name, buffer, host, service, address;
3123 Lisp_Object filter, sentinel;
3124 int is_non_blocking_client = 0;
3125 int is_server = 0, backlog = 5;
3126 int socktype;
3127 int family = -1;
3128
3129 if (nargs == 0)
3130 return Qnil;
3131
3132 /* Save arguments for process-contact and clone-process. */
3133 contact = Flist (nargs, args);
3134 GCPRO1 (contact);
3135
3136 #ifdef WINDOWSNT
3137 /* Ensure socket support is loaded if available. */
3138 init_winsock (TRUE);
3139 #endif
3140
3141 /* :type TYPE (nil: stream, datagram */
3142 tem = Fplist_get (contact, QCtype);
3143 if (NILP (tem))
3144 socktype = SOCK_STREAM;
3145 #ifdef DATAGRAM_SOCKETS
3146 else if (EQ (tem, Qdatagram))
3147 socktype = SOCK_DGRAM;
3148 #endif
3149 #ifdef HAVE_SEQPACKET
3150 else if (EQ (tem, Qseqpacket))
3151 socktype = SOCK_SEQPACKET;
3152 #endif
3153 else
3154 error ("Unsupported connection type");
3155
3156 /* :server BOOL */
3157 tem = Fplist_get (contact, QCserver);
3158 if (!NILP (tem))
3159 {
3160 /* Don't support network sockets when non-blocking mode is
3161 not available, since a blocked Emacs is not useful. */
3162 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3163 error ("Network servers not supported");
3164 #else
3165 is_server = 1;
3166 if (INTEGERP (tem))
3167 backlog = XINT (tem);
3168 #endif
3169 }
3170
3171 /* Make QCaddress an alias for :local (server) or :remote (client). */
3172 QCaddress = is_server ? QClocal : QCremote;
3173
3174 /* :nowait BOOL */
3175 if (!is_server && socktype != SOCK_DGRAM
3176 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3177 {
3178 #ifndef NON_BLOCKING_CONNECT
3179 error ("Non-blocking connect not supported");
3180 #else
3181 is_non_blocking_client = 1;
3182 #endif
3183 }
3184
3185 name = Fplist_get (contact, QCname);
3186 buffer = Fplist_get (contact, QCbuffer);
3187 filter = Fplist_get (contact, QCfilter);
3188 sentinel = Fplist_get (contact, QCsentinel);
3189
3190 CHECK_STRING (name);
3191
3192 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3193 ai.ai_socktype = socktype;
3194 ai.ai_protocol = 0;
3195 ai.ai_next = NULL;
3196 res = &ai;
3197
3198 /* :local ADDRESS or :remote ADDRESS */
3199 address = Fplist_get (contact, QCaddress);
3200 if (!NILP (address))
3201 {
3202 host = service = Qnil;
3203
3204 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3205 error ("Malformed :address");
3206 ai.ai_family = family;
3207 ai.ai_addr = alloca (ai.ai_addrlen);
3208 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3209 goto open_socket;
3210 }
3211
3212 /* :family FAMILY -- nil (for Inet), local, or integer. */
3213 tem = Fplist_get (contact, QCfamily);
3214 if (NILP (tem))
3215 {
3216 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3217 family = AF_UNSPEC;
3218 #else
3219 family = AF_INET;
3220 #endif
3221 }
3222 #ifdef HAVE_LOCAL_SOCKETS
3223 else if (EQ (tem, Qlocal))
3224 family = AF_LOCAL;
3225 #endif
3226 #ifdef AF_INET6
3227 else if (EQ (tem, Qipv6))
3228 family = AF_INET6;
3229 #endif
3230 else if (EQ (tem, Qipv4))
3231 family = AF_INET;
3232 else if (INTEGERP (tem))
3233 family = XINT (tem);
3234 else
3235 error ("Unknown address family");
3236
3237 ai.ai_family = family;
3238
3239 /* :service SERVICE -- string, integer (port number), or t (random port). */
3240 service = Fplist_get (contact, QCservice);
3241
3242 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3243 host = Fplist_get (contact, QChost);
3244 if (!NILP (host))
3245 {
3246 if (EQ (host, Qlocal))
3247 /* Depending on setup, "localhost" may map to different IPv4 and/or
3248 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3249 host = build_string ("127.0.0.1");
3250 CHECK_STRING (host);
3251 }
3252
3253 #ifdef HAVE_LOCAL_SOCKETS
3254 if (family == AF_LOCAL)
3255 {
3256 if (!NILP (host))
3257 {
3258 message (":family local ignores the :host \"%s\" property",
3259 SDATA (host));
3260 contact = Fplist_put (contact, QChost, Qnil);
3261 host = Qnil;
3262 }
3263 CHECK_STRING (service);
3264 memset (&address_un, 0, sizeof address_un);
3265 address_un.sun_family = AF_LOCAL;
3266 strncpy (address_un.sun_path, SSDATA (service), sizeof address_un.sun_path);
3267 ai.ai_addr = (struct sockaddr *) &address_un;
3268 ai.ai_addrlen = sizeof address_un;
3269 goto open_socket;
3270 }
3271 #endif
3272
3273 /* Slow down polling to every ten seconds.
3274 Some kernels have a bug which causes retrying connect to fail
3275 after a connect. Polling can interfere with gethostbyname too. */
3276 #ifdef POLL_FOR_INPUT
3277 if (socktype != SOCK_DGRAM)
3278 {
3279 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3280 bind_polling_period (10);
3281 }
3282 #endif
3283
3284 #ifdef HAVE_GETADDRINFO
3285 /* If we have a host, use getaddrinfo to resolve both host and service.
3286 Otherwise, use getservbyname to lookup the service. */
3287 if (!NILP (host))
3288 {
3289
3290 /* SERVICE can either be a string or int.
3291 Convert to a C string for later use by getaddrinfo. */
3292 if (EQ (service, Qt))
3293 portstring = "0";
3294 else if (INTEGERP (service))
3295 {
3296 sprintf (portbuf, "%ld", (long) XINT (service));
3297 portstring = portbuf;
3298 }
3299 else
3300 {
3301 CHECK_STRING (service);
3302 portstring = SSDATA (service);
3303 }
3304
3305 immediate_quit = 1;
3306 QUIT;
3307 memset (&hints, 0, sizeof (hints));
3308 hints.ai_flags = 0;
3309 hints.ai_family = family;
3310 hints.ai_socktype = socktype;
3311 hints.ai_protocol = 0;
3312
3313 #ifdef HAVE_RES_INIT
3314 res_init ();
3315 #endif
3316
3317 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3318 if (ret)
3319 #ifdef HAVE_GAI_STRERROR
3320 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3321 #else
3322 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3323 #endif
3324 immediate_quit = 0;
3325
3326 goto open_socket;
3327 }
3328 #endif /* HAVE_GETADDRINFO */
3329
3330 /* We end up here if getaddrinfo is not defined, or in case no hostname
3331 has been specified (e.g. for a local server process). */
3332
3333 if (EQ (service, Qt))
3334 port = 0;
3335 else if (INTEGERP (service))
3336 port = htons ((unsigned short) XINT (service));
3337 else
3338 {
3339 struct servent *svc_info;
3340 CHECK_STRING (service);
3341 svc_info = getservbyname (SSDATA (service),
3342 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3343 if (svc_info == 0)
3344 error ("Unknown service: %s", SDATA (service));
3345 port = svc_info->s_port;
3346 }
3347
3348 memset (&address_in, 0, sizeof address_in);
3349 address_in.sin_family = family;
3350 address_in.sin_addr.s_addr = INADDR_ANY;
3351 address_in.sin_port = port;
3352
3353 #ifndef HAVE_GETADDRINFO
3354 if (!NILP (host))
3355 {
3356 struct hostent *host_info_ptr;
3357
3358 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3359 as it may `hang' Emacs for a very long time. */
3360 immediate_quit = 1;
3361 QUIT;
3362
3363 #ifdef HAVE_RES_INIT
3364 res_init ();
3365 #endif
3366
3367 host_info_ptr = gethostbyname (SDATA (host));
3368 immediate_quit = 0;
3369
3370 if (host_info_ptr)
3371 {
3372 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3373 host_info_ptr->h_length);
3374 family = host_info_ptr->h_addrtype;
3375 address_in.sin_family = family;
3376 }
3377 else
3378 /* Attempt to interpret host as numeric inet address */
3379 {
3380 unsigned long numeric_addr;
3381 numeric_addr = inet_addr (SSDATA (host));
3382 if (numeric_addr == -1)
3383 error ("Unknown host \"%s\"", SDATA (host));
3384
3385 memcpy (&address_in.sin_addr, &numeric_addr,
3386 sizeof (address_in.sin_addr));
3387 }
3388
3389 }
3390 #endif /* not HAVE_GETADDRINFO */
3391
3392 ai.ai_family = family;
3393 ai.ai_addr = (struct sockaddr *) &address_in;
3394 ai.ai_addrlen = sizeof address_in;
3395
3396 open_socket:
3397
3398 /* Do this in case we never enter the for-loop below. */
3399 count1 = SPECPDL_INDEX ();
3400 s = -1;
3401
3402 for (lres = res; lres; lres = lres->ai_next)
3403 {
3404 int optn, optbits;
3405
3406 #ifdef WINDOWSNT
3407 retry_connect:
3408 #endif
3409
3410 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3411 if (s < 0)
3412 {
3413 xerrno = errno;
3414 continue;
3415 }
3416
3417 #ifdef DATAGRAM_SOCKETS
3418 if (!is_server && socktype == SOCK_DGRAM)
3419 break;
3420 #endif /* DATAGRAM_SOCKETS */
3421
3422 #ifdef NON_BLOCKING_CONNECT
3423 if (is_non_blocking_client)
3424 {
3425 #ifdef O_NONBLOCK
3426 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3427 #else
3428 ret = fcntl (s, F_SETFL, O_NDELAY);
3429 #endif
3430 if (ret < 0)
3431 {
3432 xerrno = errno;
3433 emacs_close (s);
3434 s = -1;
3435 continue;
3436 }
3437 }
3438 #endif
3439
3440 /* Make us close S if quit. */
3441 record_unwind_protect (close_file_unwind, make_number (s));
3442
3443 /* Parse network options in the arg list.
3444 We simply ignore anything which isn't a known option (including other keywords).
3445 An error is signaled if setting a known option fails. */
3446 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3447 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3448
3449 if (is_server)
3450 {
3451 /* Configure as a server socket. */
3452
3453 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3454 explicit :reuseaddr key to override this. */
3455 #ifdef HAVE_LOCAL_SOCKETS
3456 if (family != AF_LOCAL)
3457 #endif
3458 if (!(optbits & (1 << OPIX_REUSEADDR)))
3459 {
3460 int optval = 1;
3461 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3462 report_file_error ("Cannot set reuse option on server socket", Qnil);
3463 }
3464
3465 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3466 report_file_error ("Cannot bind server socket", Qnil);
3467
3468 #ifdef HAVE_GETSOCKNAME
3469 if (EQ (service, Qt))
3470 {
3471 struct sockaddr_in sa1;
3472 int len1 = sizeof (sa1);
3473 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3474 {
3475 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3476 service = make_number (ntohs (sa1.sin_port));
3477 contact = Fplist_put (contact, QCservice, service);
3478 }
3479 }
3480 #endif
3481
3482 if (socktype != SOCK_DGRAM && listen (s, backlog))
3483 report_file_error ("Cannot listen on server socket", Qnil);
3484
3485 break;
3486 }
3487
3488 immediate_quit = 1;
3489 QUIT;
3490
3491 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3492 xerrno = errno;
3493
3494 if (ret == 0 || xerrno == EISCONN)
3495 {
3496 /* The unwind-protect will be discarded afterwards.
3497 Likewise for immediate_quit. */
3498 break;
3499 }
3500
3501 #ifdef NON_BLOCKING_CONNECT
3502 #ifdef EINPROGRESS
3503 if (is_non_blocking_client && xerrno == EINPROGRESS)
3504 break;
3505 #else
3506 #ifdef EWOULDBLOCK
3507 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3508 break;
3509 #endif
3510 #endif
3511 #endif
3512
3513 #ifndef WINDOWSNT
3514 if (xerrno == EINTR)
3515 {
3516 /* Unlike most other syscalls connect() cannot be called
3517 again. (That would return EALREADY.) The proper way to
3518 wait for completion is select(). */
3519 int sc, len;
3520 SELECT_TYPE fdset;
3521 retry_select:
3522 FD_ZERO (&fdset);
3523 FD_SET (s, &fdset);
3524 QUIT;
3525 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3526 (EMACS_TIME *)0);
3527 if (sc == -1)
3528 {
3529 if (errno == EINTR)
3530 goto retry_select;
3531 else
3532 report_file_error ("select failed", Qnil);
3533 }
3534 eassert (sc > 0);
3535
3536 len = sizeof xerrno;
3537 eassert (FD_ISSET (s, &fdset));
3538 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3539 report_file_error ("getsockopt failed", Qnil);
3540 if (xerrno)
3541 errno = xerrno, report_file_error ("error during connect", Qnil);
3542 else
3543 break;
3544 }
3545 #endif /* !WINDOWSNT */
3546
3547 immediate_quit = 0;
3548
3549 /* Discard the unwind protect closing S. */
3550 specpdl_ptr = specpdl + count1;
3551 emacs_close (s);
3552 s = -1;
3553
3554 #ifdef WINDOWSNT
3555 if (xerrno == EINTR)
3556 goto retry_connect;
3557 #endif
3558 }
3559
3560 if (s >= 0)
3561 {
3562 #ifdef DATAGRAM_SOCKETS
3563 if (socktype == SOCK_DGRAM)
3564 {
3565 if (datagram_address[s].sa)
3566 abort ();
3567 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3568 datagram_address[s].len = lres->ai_addrlen;
3569 if (is_server)
3570 {
3571 Lisp_Object remote;
3572 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3573 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3574 {
3575 int rfamily, rlen;
3576 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3577 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3578 conv_lisp_to_sockaddr (rfamily, remote,
3579 datagram_address[s].sa, rlen);
3580 }
3581 }
3582 else
3583 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3584 }
3585 #endif
3586 contact = Fplist_put (contact, QCaddress,
3587 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3588 #ifdef HAVE_GETSOCKNAME
3589 if (!is_server)
3590 {
3591 struct sockaddr_in sa1;
3592 int len1 = sizeof (sa1);
3593 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3594 contact = Fplist_put (contact, QClocal,
3595 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3596 }
3597 #endif
3598 }
3599
3600 immediate_quit = 0;
3601
3602 #ifdef HAVE_GETADDRINFO
3603 if (res != &ai)
3604 {
3605 BLOCK_INPUT;
3606 freeaddrinfo (res);
3607 UNBLOCK_INPUT;
3608 }
3609 #endif
3610
3611 /* Discard the unwind protect for closing S, if any. */
3612 specpdl_ptr = specpdl + count1;
3613
3614 /* Unwind bind_polling_period and request_sigio. */
3615 unbind_to (count, Qnil);
3616
3617 if (s < 0)
3618 {
3619 /* If non-blocking got this far - and failed - assume non-blocking is
3620 not supported after all. This is probably a wrong assumption, but
3621 the normal blocking calls to open-network-stream handles this error
3622 better. */
3623 if (is_non_blocking_client)
3624 return Qnil;
3625
3626 errno = xerrno;
3627 if (is_server)
3628 report_file_error ("make server process failed", contact);
3629 else
3630 report_file_error ("make client process failed", contact);
3631 }
3632
3633 inch = s;
3634 outch = s;
3635
3636 if (!NILP (buffer))
3637 buffer = Fget_buffer_create (buffer);
3638 proc = make_process (name);
3639
3640 chan_process[inch] = proc;
3641
3642 #ifdef O_NONBLOCK
3643 fcntl (inch, F_SETFL, O_NONBLOCK);
3644 #else
3645 #ifdef O_NDELAY
3646 fcntl (inch, F_SETFL, O_NDELAY);
3647 #endif
3648 #endif
3649
3650 p = XPROCESS (proc);
3651
3652 p->childp = contact;
3653 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3654 p->type = Qnetwork;
3655
3656 p->buffer = buffer;
3657 p->sentinel = sentinel;
3658 p->filter = filter;
3659 p->log = Fplist_get (contact, QClog);
3660 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3661 p->kill_without_query = 1;
3662 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3663 p->command = Qt;
3664 p->pid = 0;
3665 p->infd = inch;
3666 p->outfd = outch;
3667 if (is_server && socktype != SOCK_DGRAM)
3668 p->status = Qlisten;
3669
3670 /* Make the process marker point into the process buffer (if any). */
3671 if (BUFFERP (buffer))
3672 set_marker_both (p->mark, buffer,
3673 BUF_ZV (XBUFFER (buffer)),
3674 BUF_ZV_BYTE (XBUFFER (buffer)));
3675
3676 #ifdef NON_BLOCKING_CONNECT
3677 if (is_non_blocking_client)
3678 {
3679 /* We may get here if connect did succeed immediately. However,
3680 in that case, we still need to signal this like a non-blocking
3681 connection. */
3682 p->status = Qconnect;
3683 if (!FD_ISSET (inch, &connect_wait_mask))
3684 {
3685 FD_SET (inch, &connect_wait_mask);
3686 FD_SET (inch, &write_mask);
3687 num_pending_connects++;
3688 }
3689 }
3690 else
3691 #endif
3692 /* A server may have a client filter setting of Qt, but it must
3693 still listen for incoming connects unless it is stopped. */
3694 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3695 || (EQ (p->status, Qlisten) && NILP (p->command)))
3696 {
3697 FD_SET (inch, &input_wait_mask);
3698 FD_SET (inch, &non_keyboard_wait_mask);
3699 }
3700
3701 if (inch > max_process_desc)
3702 max_process_desc = inch;
3703
3704 tem = Fplist_member (contact, QCcoding);
3705 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3706 tem = Qnil; /* No error message (too late!). */
3707
3708 {
3709 /* Setup coding systems for communicating with the network stream. */
3710 struct gcpro inner_gcpro1;
3711 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3712 Lisp_Object coding_systems = Qt;
3713 Lisp_Object fargs[5], val;
3714
3715 if (!NILP (tem))
3716 {
3717 val = XCAR (XCDR (tem));
3718 if (CONSP (val))
3719 val = XCAR (val);
3720 }
3721 else if (!NILP (Vcoding_system_for_read))
3722 val = Vcoding_system_for_read;
3723 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3724 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3725 /* We dare not decode end-of-line format by setting VAL to
3726 Qraw_text, because the existing Emacs Lisp libraries
3727 assume that they receive bare code including a sequene of
3728 CR LF. */
3729 val = Qnil;
3730 else
3731 {
3732 if (NILP (host) || NILP (service))
3733 coding_systems = Qnil;
3734 else
3735 {
3736 fargs[0] = Qopen_network_stream, fargs[1] = name,
3737 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3738 GCPRO1_VAR (proc, inner_gcpro);
3739 coding_systems = Ffind_operation_coding_system (5, fargs);
3740 UNGCPRO_VAR (inner_gcpro);
3741 }
3742 if (CONSP (coding_systems))
3743 val = XCAR (coding_systems);
3744 else if (CONSP (Vdefault_process_coding_system))
3745 val = XCAR (Vdefault_process_coding_system);
3746 else
3747 val = Qnil;
3748 }
3749 p->decode_coding_system = val;
3750
3751 if (!NILP (tem))
3752 {
3753 val = XCAR (XCDR (tem));
3754 if (CONSP (val))
3755 val = XCDR (val);
3756 }
3757 else if (!NILP (Vcoding_system_for_write))
3758 val = Vcoding_system_for_write;
3759 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3760 val = Qnil;
3761 else
3762 {
3763 if (EQ (coding_systems, Qt))
3764 {
3765 if (NILP (host) || NILP (service))
3766 coding_systems = Qnil;
3767 else
3768 {
3769 fargs[0] = Qopen_network_stream, fargs[1] = name,
3770 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3771 GCPRO1_VAR (proc, inner_gcpro);
3772 coding_systems = Ffind_operation_coding_system (5, fargs);
3773 UNGCPRO_VAR (inner_gcpro);
3774 }
3775 }
3776 if (CONSP (coding_systems))
3777 val = XCDR (coding_systems);
3778 else if (CONSP (Vdefault_process_coding_system))
3779 val = XCDR (Vdefault_process_coding_system);
3780 else
3781 val = Qnil;
3782 }
3783 p->encode_coding_system = val;
3784 }
3785 setup_process_coding_systems (proc);
3786
3787 p->decoding_buf = empty_unibyte_string;
3788 p->decoding_carryover = 0;
3789 p->encoding_buf = empty_unibyte_string;
3790
3791 p->inherit_coding_system_flag
3792 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3793
3794 UNGCPRO;
3795 return proc;
3796 }
3797
3798 \f
3799 #if defined(HAVE_NET_IF_H)
3800
3801 #ifdef SIOCGIFCONF
3802 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3803 doc: /* Return an alist of all network interfaces and their network address.
3804 Each element is a cons, the car of which is a string containing the
3805 interface name, and the cdr is the network address in internal
3806 format; see the description of ADDRESS in `make-network-process'. */)
3807 (void)
3808 {
3809 struct ifconf ifconf;
3810 struct ifreq *ifreqs = NULL;
3811 int ifaces = 0;
3812 int buf_size, s;
3813 Lisp_Object res;
3814
3815 s = socket (AF_INET, SOCK_STREAM, 0);
3816 if (s < 0)
3817 return Qnil;
3818
3819 again:
3820 ifaces += 25;
3821 buf_size = ifaces * sizeof (ifreqs[0]);
3822 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3823 if (!ifreqs)
3824 {
3825 close (s);
3826 return Qnil;
3827 }
3828
3829 ifconf.ifc_len = buf_size;
3830 ifconf.ifc_req = ifreqs;
3831 if (ioctl (s, SIOCGIFCONF, &ifconf))
3832 {
3833 close (s);
3834 return Qnil;
3835 }
3836
3837 if (ifconf.ifc_len == buf_size)
3838 goto again;
3839
3840 close (s);
3841 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3842
3843 res = Qnil;
3844 while (--ifaces >= 0)
3845 {
3846 struct ifreq *ifq = &ifreqs[ifaces];
3847 char namebuf[sizeof (ifq->ifr_name) + 1];
3848 if (ifq->ifr_addr.sa_family != AF_INET)
3849 continue;
3850 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3851 namebuf[sizeof (ifq->ifr_name)] = 0;
3852 res = Fcons (Fcons (build_string (namebuf),
3853 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3854 sizeof (struct sockaddr))),
3855 res);
3856 }
3857
3858 return res;
3859 }
3860 #endif /* SIOCGIFCONF */
3861
3862 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3863
3864 struct ifflag_def {
3865 int flag_bit;
3866 const char *flag_sym;
3867 };
3868
3869 static const struct ifflag_def ifflag_table[] = {
3870 #ifdef IFF_UP
3871 { IFF_UP, "up" },
3872 #endif
3873 #ifdef IFF_BROADCAST
3874 { IFF_BROADCAST, "broadcast" },
3875 #endif
3876 #ifdef IFF_DEBUG
3877 { IFF_DEBUG, "debug" },
3878 #endif
3879 #ifdef IFF_LOOPBACK
3880 { IFF_LOOPBACK, "loopback" },
3881 #endif
3882 #ifdef IFF_POINTOPOINT
3883 { IFF_POINTOPOINT, "pointopoint" },
3884 #endif
3885 #ifdef IFF_RUNNING
3886 { IFF_RUNNING, "running" },
3887 #endif
3888 #ifdef IFF_NOARP
3889 { IFF_NOARP, "noarp" },
3890 #endif
3891 #ifdef IFF_PROMISC
3892 { IFF_PROMISC, "promisc" },
3893 #endif
3894 #ifdef IFF_NOTRAILERS
3895 { IFF_NOTRAILERS, "notrailers" },
3896 #endif
3897 #ifdef IFF_ALLMULTI
3898 { IFF_ALLMULTI, "allmulti" },
3899 #endif
3900 #ifdef IFF_MASTER
3901 { IFF_MASTER, "master" },
3902 #endif
3903 #ifdef IFF_SLAVE
3904 { IFF_SLAVE, "slave" },
3905 #endif
3906 #ifdef IFF_MULTICAST
3907 { IFF_MULTICAST, "multicast" },
3908 #endif
3909 #ifdef IFF_PORTSEL
3910 { IFF_PORTSEL, "portsel" },
3911 #endif
3912 #ifdef IFF_AUTOMEDIA
3913 { IFF_AUTOMEDIA, "automedia" },
3914 #endif
3915 #ifdef IFF_DYNAMIC
3916 { IFF_DYNAMIC, "dynamic" },
3917 #endif
3918 #ifdef IFF_OACTIVE
3919 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3920 #endif
3921 #ifdef IFF_SIMPLEX
3922 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3923 #endif
3924 #ifdef IFF_LINK0
3925 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3926 #endif
3927 #ifdef IFF_LINK1
3928 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3929 #endif
3930 #ifdef IFF_LINK2
3931 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3932 #endif
3933 { 0, 0 }
3934 };
3935
3936 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3937 doc: /* Return information about network interface named IFNAME.
3938 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3939 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3940 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3941 FLAGS is the current flags of the interface. */)
3942 (Lisp_Object ifname)
3943 {
3944 struct ifreq rq;
3945 Lisp_Object res = Qnil;
3946 Lisp_Object elt;
3947 int s;
3948 int any = 0;
3949
3950 CHECK_STRING (ifname);
3951
3952 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
3953 strncpy (rq.ifr_name, SSDATA (ifname), sizeof (rq.ifr_name));
3954
3955 s = socket (AF_INET, SOCK_STREAM, 0);
3956 if (s < 0)
3957 return Qnil;
3958
3959 elt = Qnil;
3960 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3961 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3962 {
3963 int flags = rq.ifr_flags;
3964 const struct ifflag_def *fp;
3965 int fnum;
3966
3967 any++;
3968 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3969 {
3970 if (flags & fp->flag_bit)
3971 {
3972 elt = Fcons (intern (fp->flag_sym), elt);
3973 flags -= fp->flag_bit;
3974 }
3975 }
3976 for (fnum = 0; flags && fnum < 32; fnum++)
3977 {
3978 if (flags & (1 << fnum))
3979 {
3980 elt = Fcons (make_number (fnum), elt);
3981 }
3982 }
3983 }
3984 #endif
3985 res = Fcons (elt, res);
3986
3987 elt = Qnil;
3988 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3989 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3990 {
3991 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3992 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3993 int n;
3994
3995 any++;
3996 for (n = 0; n < 6; n++)
3997 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3998 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3999 }
4000 #endif
4001 res = Fcons (elt, res);
4002
4003 elt = Qnil;
4004 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4005 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4006 {
4007 any++;
4008 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4009 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4010 #else
4011 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4012 #endif
4013 }
4014 #endif
4015 res = Fcons (elt, res);
4016
4017 elt = Qnil;
4018 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4019 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4020 {
4021 any++;
4022 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4023 }
4024 #endif
4025 res = Fcons (elt, res);
4026
4027 elt = Qnil;
4028 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4029 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4030 {
4031 any++;
4032 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4033 }
4034 #endif
4035 res = Fcons (elt, res);
4036
4037 close (s);
4038
4039 return any ? res : Qnil;
4040 }
4041 #endif
4042 #endif /* defined(HAVE_NET_IF_H) */
4043
4044 /* Turn off input and output for process PROC. */
4045
4046 void
4047 deactivate_process (Lisp_Object proc)
4048 {
4049 register int inchannel, outchannel;
4050 register struct Lisp_Process *p = XPROCESS (proc);
4051
4052 inchannel = p->infd;
4053 outchannel = p->outfd;
4054
4055 #ifdef ADAPTIVE_READ_BUFFERING
4056 if (p->read_output_delay > 0)
4057 {
4058 if (--process_output_delay_count < 0)
4059 process_output_delay_count = 0;
4060 p->read_output_delay = 0;
4061 p->read_output_skip = 0;
4062 }
4063 #endif
4064
4065 if (inchannel >= 0)
4066 {
4067 /* Beware SIGCHLD hereabouts. */
4068 flush_pending_output (inchannel);
4069 emacs_close (inchannel);
4070 if (outchannel >= 0 && outchannel != inchannel)
4071 emacs_close (outchannel);
4072
4073 p->infd = -1;
4074 p->outfd = -1;
4075 #ifdef DATAGRAM_SOCKETS
4076 if (DATAGRAM_CHAN_P (inchannel))
4077 {
4078 xfree (datagram_address[inchannel].sa);
4079 datagram_address[inchannel].sa = 0;
4080 datagram_address[inchannel].len = 0;
4081 }
4082 #endif
4083 chan_process[inchannel] = Qnil;
4084 FD_CLR (inchannel, &input_wait_mask);
4085 FD_CLR (inchannel, &non_keyboard_wait_mask);
4086 #ifdef NON_BLOCKING_CONNECT
4087 if (FD_ISSET (inchannel, &connect_wait_mask))
4088 {
4089 FD_CLR (inchannel, &connect_wait_mask);
4090 FD_CLR (inchannel, &write_mask);
4091 if (--num_pending_connects < 0)
4092 abort ();
4093 }
4094 #endif
4095 if (inchannel == max_process_desc)
4096 {
4097 int i;
4098 /* We just closed the highest-numbered process input descriptor,
4099 so recompute the highest-numbered one now. */
4100 max_process_desc = 0;
4101 for (i = 0; i < MAXDESC; i++)
4102 if (!NILP (chan_process[i]))
4103 max_process_desc = i;
4104 }
4105 }
4106 }
4107
4108 \f
4109 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4110 0, 4, 0,
4111 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4112 It is read into the process' buffers or given to their filter functions.
4113 Non-nil arg PROCESS means do not return until some output has been received
4114 from PROCESS.
4115
4116 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4117 and milliseconds to wait; return after that much time whether or not
4118 there is any subprocess output. If SECONDS is a floating point number,
4119 it specifies a fractional number of seconds to wait.
4120 The MILLISEC argument is obsolete and should be avoided.
4121
4122 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4123 from PROCESS, suspending reading output from other processes.
4124 If JUST-THIS-ONE is an integer, don't run any timers either.
4125 Return non-nil if we received any output before the timeout expired. */)
4126 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4127 {
4128 int secs, usecs = 0;
4129
4130 if (! NILP (process))
4131 CHECK_PROCESS (process);
4132 else
4133 just_this_one = Qnil;
4134
4135 if (!NILP (millisec))
4136 { /* Obsolete calling convention using integers rather than floats. */
4137 CHECK_NUMBER (millisec);
4138 if (NILP (seconds))
4139 seconds = make_float (XINT (millisec) / 1000.0);
4140 else
4141 {
4142 CHECK_NUMBER (seconds);
4143 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4144 }
4145 }
4146
4147 if (!NILP (seconds))
4148 {
4149 if (INTEGERP (seconds))
4150 secs = XINT (seconds);
4151 else if (FLOATP (seconds))
4152 {
4153 double timeout = XFLOAT_DATA (seconds);
4154 secs = (int) timeout;
4155 usecs = (int) ((timeout - (double) secs) * 1000000);
4156 }
4157 else
4158 wrong_type_argument (Qnumberp, seconds);
4159
4160 if (secs < 0 || (secs == 0 && usecs == 0))
4161 secs = -1, usecs = 0;
4162 }
4163 else
4164 secs = NILP (process) ? -1 : 0;
4165
4166 return
4167 (wait_reading_process_output (secs, usecs, 0, 0,
4168 Qnil,
4169 !NILP (process) ? XPROCESS (process) : NULL,
4170 NILP (just_this_one) ? 0 :
4171 !INTEGERP (just_this_one) ? 1 : -1)
4172 ? Qt : Qnil);
4173 }
4174
4175 /* Accept a connection for server process SERVER on CHANNEL. */
4176
4177 static int connect_counter = 0;
4178
4179 static void
4180 server_accept_connection (Lisp_Object server, int channel)
4181 {
4182 Lisp_Object proc, caller, name, buffer;
4183 Lisp_Object contact, host, service;
4184 struct Lisp_Process *ps= XPROCESS (server);
4185 struct Lisp_Process *p;
4186 int s;
4187 union u_sockaddr {
4188 struct sockaddr sa;
4189 struct sockaddr_in in;
4190 #ifdef AF_INET6
4191 struct sockaddr_in6 in6;
4192 #endif
4193 #ifdef HAVE_LOCAL_SOCKETS
4194 struct sockaddr_un un;
4195 #endif
4196 } saddr;
4197 int len = sizeof saddr;
4198
4199 s = accept (channel, &saddr.sa, &len);
4200
4201 if (s < 0)
4202 {
4203 int code = errno;
4204
4205 if (code == EAGAIN)
4206 return;
4207 #ifdef EWOULDBLOCK
4208 if (code == EWOULDBLOCK)
4209 return;
4210 #endif
4211
4212 if (!NILP (ps->log))
4213 call3 (ps->log, server, Qnil,
4214 concat3 (build_string ("accept failed with code"),
4215 Fnumber_to_string (make_number (code)),
4216 build_string ("\n")));
4217 return;
4218 }
4219
4220 connect_counter++;
4221
4222 /* Setup a new process to handle the connection. */
4223
4224 /* Generate a unique identification of the caller, and build contact
4225 information for this process. */
4226 host = Qt;
4227 service = Qnil;
4228 switch (saddr.sa.sa_family)
4229 {
4230 case AF_INET:
4231 {
4232 Lisp_Object args[5];
4233 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4234 args[0] = build_string ("%d.%d.%d.%d");
4235 args[1] = make_number (*ip++);
4236 args[2] = make_number (*ip++);
4237 args[3] = make_number (*ip++);
4238 args[4] = make_number (*ip++);
4239 host = Fformat (5, args);
4240 service = make_number (ntohs (saddr.in.sin_port));
4241
4242 args[0] = build_string (" <%s:%d>");
4243 args[1] = host;
4244 args[2] = service;
4245 caller = Fformat (3, args);
4246 }
4247 break;
4248
4249 #ifdef AF_INET6
4250 case AF_INET6:
4251 {
4252 Lisp_Object args[9];
4253 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4254 int i;
4255 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4256 for (i = 0; i < 8; i++)
4257 args[i+1] = make_number (ntohs (ip6[i]));
4258 host = Fformat (9, args);
4259 service = make_number (ntohs (saddr.in.sin_port));
4260
4261 args[0] = build_string (" <[%s]:%d>");
4262 args[1] = host;
4263 args[2] = service;
4264 caller = Fformat (3, args);
4265 }
4266 break;
4267 #endif
4268
4269 #ifdef HAVE_LOCAL_SOCKETS
4270 case AF_LOCAL:
4271 #endif
4272 default:
4273 caller = Fnumber_to_string (make_number (connect_counter));
4274 caller = concat3 (build_string (" <"), caller, build_string (">"));
4275 break;
4276 }
4277
4278 /* Create a new buffer name for this process if it doesn't have a
4279 filter. The new buffer name is based on the buffer name or
4280 process name of the server process concatenated with the caller
4281 identification. */
4282
4283 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4284 buffer = Qnil;
4285 else
4286 {
4287 buffer = ps->buffer;
4288 if (!NILP (buffer))
4289 buffer = Fbuffer_name (buffer);
4290 else
4291 buffer = ps->name;
4292 if (!NILP (buffer))
4293 {
4294 buffer = concat2 (buffer, caller);
4295 buffer = Fget_buffer_create (buffer);
4296 }
4297 }
4298
4299 /* Generate a unique name for the new server process. Combine the
4300 server process name with the caller identification. */
4301
4302 name = concat2 (ps->name, caller);
4303 proc = make_process (name);
4304
4305 chan_process[s] = proc;
4306
4307 #ifdef O_NONBLOCK
4308 fcntl (s, F_SETFL, O_NONBLOCK);
4309 #else
4310 #ifdef O_NDELAY
4311 fcntl (s, F_SETFL, O_NDELAY);
4312 #endif
4313 #endif
4314
4315 p = XPROCESS (proc);
4316
4317 /* Build new contact information for this setup. */
4318 contact = Fcopy_sequence (ps->childp);
4319 contact = Fplist_put (contact, QCserver, Qnil);
4320 contact = Fplist_put (contact, QChost, host);
4321 if (!NILP (service))
4322 contact = Fplist_put (contact, QCservice, service);
4323 contact = Fplist_put (contact, QCremote,
4324 conv_sockaddr_to_lisp (&saddr.sa, len));
4325 #ifdef HAVE_GETSOCKNAME
4326 len = sizeof saddr;
4327 if (getsockname (s, &saddr.sa, &len) == 0)
4328 contact = Fplist_put (contact, QClocal,
4329 conv_sockaddr_to_lisp (&saddr.sa, len));
4330 #endif
4331
4332 p->childp = contact;
4333 p->plist = Fcopy_sequence (ps->plist);
4334 p->type = Qnetwork;
4335
4336 p->buffer = buffer;
4337 p->sentinel = ps->sentinel;
4338 p->filter = ps->filter;
4339 p->command = Qnil;
4340 p->pid = 0;
4341 p->infd = s;
4342 p->outfd = s;
4343 p->status = Qrun;
4344
4345 /* Client processes for accepted connections are not stopped initially. */
4346 if (!EQ (p->filter, Qt))
4347 {
4348 FD_SET (s, &input_wait_mask);
4349 FD_SET (s, &non_keyboard_wait_mask);
4350 }
4351
4352 if (s > max_process_desc)
4353 max_process_desc = s;
4354
4355 /* Setup coding system for new process based on server process.
4356 This seems to be the proper thing to do, as the coding system
4357 of the new process should reflect the settings at the time the
4358 server socket was opened; not the current settings. */
4359
4360 p->decode_coding_system = ps->decode_coding_system;
4361 p->encode_coding_system = ps->encode_coding_system;
4362 setup_process_coding_systems (proc);
4363
4364 p->decoding_buf = empty_unibyte_string;
4365 p->decoding_carryover = 0;
4366 p->encoding_buf = empty_unibyte_string;
4367
4368 p->inherit_coding_system_flag
4369 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4370
4371 if (!NILP (ps->log))
4372 call3 (ps->log, server, proc,
4373 concat3 (build_string ("accept from "),
4374 (STRINGP (host) ? host : build_string ("-")),
4375 build_string ("\n")));
4376
4377 if (!NILP (p->sentinel))
4378 exec_sentinel (proc,
4379 concat3 (build_string ("open from "),
4380 (STRINGP (host) ? host : build_string ("-")),
4381 build_string ("\n")));
4382 }
4383
4384 /* This variable is different from waiting_for_input in keyboard.c.
4385 It is used to communicate to a lisp process-filter/sentinel (via the
4386 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4387 for user-input when that process-filter was called.
4388 waiting_for_input cannot be used as that is by definition 0 when
4389 lisp code is being evalled.
4390 This is also used in record_asynch_buffer_change.
4391 For that purpose, this must be 0
4392 when not inside wait_reading_process_output. */
4393 static int waiting_for_user_input_p;
4394
4395 static Lisp_Object
4396 wait_reading_process_output_unwind (Lisp_Object data)
4397 {
4398 waiting_for_user_input_p = XINT (data);
4399 return Qnil;
4400 }
4401
4402 /* This is here so breakpoints can be put on it. */
4403 static void
4404 wait_reading_process_output_1 (void)
4405 {
4406 }
4407
4408 /* Use a wrapper around select to work around a bug in gdb 5.3.
4409 Normally, the wrapper is optimized away by inlining.
4410
4411 If emacs is stopped inside select, the gdb backtrace doesn't
4412 show the function which called select, so it is practically
4413 impossible to step through wait_reading_process_output. */
4414
4415 #ifndef select
4416 static INLINE int
4417 select_wrapper (int n, fd_set *rfd, fd_set *wfd, fd_set *xfd, struct timeval *tmo)
4418 {
4419 return select (n, rfd, wfd, xfd, tmo);
4420 }
4421 #define select select_wrapper
4422 #endif
4423
4424 /* Read and dispose of subprocess output while waiting for timeout to
4425 elapse and/or keyboard input to be available.
4426
4427 TIME_LIMIT is:
4428 timeout in seconds, or
4429 zero for no limit, or
4430 -1 means gobble data immediately available but don't wait for any.
4431
4432 MICROSECS is:
4433 an additional duration to wait, measured in microseconds.
4434 If this is nonzero and time_limit is 0, then the timeout
4435 consists of MICROSECS only.
4436
4437 READ_KBD is a lisp value:
4438 0 to ignore keyboard input, or
4439 1 to return when input is available, or
4440 -1 meaning caller will actually read the input, so don't throw to
4441 the quit handler, or
4442
4443 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4444 output that arrives.
4445
4446 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4447 (and gobble terminal input into the buffer if any arrives).
4448
4449 If WAIT_PROC is specified, wait until something arrives from that
4450 process. The return value is true if we read some input from
4451 that process.
4452
4453 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4454 (suspending output from other processes). A negative value
4455 means don't run any timers either.
4456
4457 If WAIT_PROC is specified, then the function returns true if we
4458 received input from that process before the timeout elapsed.
4459 Otherwise, return true if we received input from any process. */
4460
4461 int
4462 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
4463 int do_display,
4464 Lisp_Object wait_for_cell,
4465 struct Lisp_Process *wait_proc, int just_wait_proc)
4466 {
4467 register int channel, nfds;
4468 SELECT_TYPE Available;
4469 SELECT_TYPE Writeok;
4470 int check_write;
4471 int check_delay, no_avail;
4472 int xerrno;
4473 Lisp_Object proc;
4474 EMACS_TIME timeout, end_time;
4475 int wait_channel = -1;
4476 int got_some_input = 0;
4477 int count = SPECPDL_INDEX ();
4478
4479 FD_ZERO (&Available);
4480 FD_ZERO (&Writeok);
4481
4482 if (time_limit == 0 && microsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4483 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4484 message ("Blocking call to accept-process-output with quit inhibited!!");
4485
4486 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4487 if (wait_proc != NULL)
4488 wait_channel = wait_proc->infd;
4489
4490 record_unwind_protect (wait_reading_process_output_unwind,
4491 make_number (waiting_for_user_input_p));
4492 waiting_for_user_input_p = read_kbd;
4493
4494 /* Since we may need to wait several times,
4495 compute the absolute time to return at. */
4496 if (time_limit || microsecs)
4497 {
4498 EMACS_GET_TIME (end_time);
4499 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4500 EMACS_ADD_TIME (end_time, end_time, timeout);
4501 }
4502
4503 while (1)
4504 {
4505 int timeout_reduced_for_timers = 0;
4506
4507 /* If calling from keyboard input, do not quit
4508 since we want to return C-g as an input character.
4509 Otherwise, do pending quit if requested. */
4510 if (read_kbd >= 0)
4511 QUIT;
4512 #ifdef SYNC_INPUT
4513 else
4514 process_pending_signals ();
4515 #endif
4516
4517 /* Exit now if the cell we're waiting for became non-nil. */
4518 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4519 break;
4520
4521 /* Compute time from now till when time limit is up */
4522 /* Exit if already run out */
4523 if (time_limit == -1)
4524 {
4525 /* -1 specified for timeout means
4526 gobble output available now
4527 but don't wait at all. */
4528
4529 EMACS_SET_SECS_USECS (timeout, 0, 0);
4530 }
4531 else if (time_limit || microsecs)
4532 {
4533 EMACS_GET_TIME (timeout);
4534 EMACS_SUB_TIME (timeout, end_time, timeout);
4535 if (EMACS_TIME_NEG_P (timeout))
4536 break;
4537 }
4538 else
4539 {
4540 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4541 }
4542
4543 /* Normally we run timers here.
4544 But not if wait_for_cell; in those cases,
4545 the wait is supposed to be short,
4546 and those callers cannot handle running arbitrary Lisp code here. */
4547 if (NILP (wait_for_cell)
4548 && just_wait_proc >= 0)
4549 {
4550 EMACS_TIME timer_delay;
4551
4552 do
4553 {
4554 int old_timers_run = timers_run;
4555 struct buffer *old_buffer = current_buffer;
4556 Lisp_Object old_window = selected_window;
4557
4558 timer_delay = timer_check (1);
4559
4560 /* If a timer has run, this might have changed buffers
4561 an alike. Make read_key_sequence aware of that. */
4562 if (timers_run != old_timers_run
4563 && (old_buffer != current_buffer
4564 || !EQ (old_window, selected_window))
4565 && waiting_for_user_input_p == -1)
4566 record_asynch_buffer_change ();
4567
4568 if (timers_run != old_timers_run && do_display)
4569 /* We must retry, since a timer may have requeued itself
4570 and that could alter the time_delay. */
4571 redisplay_preserve_echo_area (9);
4572 else
4573 break;
4574 }
4575 while (!detect_input_pending ());
4576
4577 /* If there is unread keyboard input, also return. */
4578 if (read_kbd != 0
4579 && requeued_events_pending_p ())
4580 break;
4581
4582 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4583 {
4584 EMACS_TIME difference;
4585 EMACS_SUB_TIME (difference, timer_delay, timeout);
4586 if (EMACS_TIME_NEG_P (difference))
4587 {
4588 timeout = timer_delay;
4589 timeout_reduced_for_timers = 1;
4590 }
4591 }
4592 /* If time_limit is -1, we are not going to wait at all. */
4593 else if (time_limit != -1)
4594 {
4595 /* This is so a breakpoint can be put here. */
4596 wait_reading_process_output_1 ();
4597 }
4598 }
4599
4600 /* Cause C-g and alarm signals to take immediate action,
4601 and cause input available signals to zero out timeout.
4602
4603 It is important that we do this before checking for process
4604 activity. If we get a SIGCHLD after the explicit checks for
4605 process activity, timeout is the only way we will know. */
4606 if (read_kbd < 0)
4607 set_waiting_for_input (&timeout);
4608
4609 /* If status of something has changed, and no input is
4610 available, notify the user of the change right away. After
4611 this explicit check, we'll let the SIGCHLD handler zap
4612 timeout to get our attention. */
4613 if (update_tick != process_tick)
4614 {
4615 SELECT_TYPE Atemp;
4616 SELECT_TYPE Ctemp;
4617
4618 if (kbd_on_hold_p ())
4619 FD_ZERO (&Atemp);
4620 else
4621 Atemp = input_wait_mask;
4622 Ctemp = write_mask;
4623
4624 EMACS_SET_SECS_USECS (timeout, 0, 0);
4625 if ((select (max (max_process_desc, max_input_desc) + 1,
4626 &Atemp,
4627 #ifdef NON_BLOCKING_CONNECT
4628 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4629 #else
4630 (SELECT_TYPE *)0,
4631 #endif
4632 (SELECT_TYPE *)0, &timeout)
4633 <= 0))
4634 {
4635 /* It's okay for us to do this and then continue with
4636 the loop, since timeout has already been zeroed out. */
4637 clear_waiting_for_input ();
4638 status_notify (NULL);
4639 if (do_display) redisplay_preserve_echo_area (13);
4640 }
4641 }
4642
4643 /* Don't wait for output from a non-running process. Just
4644 read whatever data has already been received. */
4645 if (wait_proc && wait_proc->raw_status_new)
4646 update_status (wait_proc);
4647 if (wait_proc
4648 && ! EQ (wait_proc->status, Qrun)
4649 && ! EQ (wait_proc->status, Qconnect))
4650 {
4651 int nread, total_nread = 0;
4652
4653 clear_waiting_for_input ();
4654 XSETPROCESS (proc, wait_proc);
4655
4656 /* Read data from the process, until we exhaust it. */
4657 while (wait_proc->infd >= 0)
4658 {
4659 nread = read_process_output (proc, wait_proc->infd);
4660
4661 if (nread == 0)
4662 break;
4663
4664 if (0 < nread)
4665 {
4666 total_nread += nread;
4667 got_some_input = 1;
4668 }
4669 #ifdef EIO
4670 else if (nread == -1 && EIO == errno)
4671 break;
4672 #endif
4673 #ifdef EAGAIN
4674 else if (nread == -1 && EAGAIN == errno)
4675 break;
4676 #endif
4677 #ifdef EWOULDBLOCK
4678 else if (nread == -1 && EWOULDBLOCK == errno)
4679 break;
4680 #endif
4681 }
4682 if (total_nread > 0 && do_display)
4683 redisplay_preserve_echo_area (10);
4684
4685 break;
4686 }
4687
4688 /* Wait till there is something to do */
4689
4690 if (wait_proc && just_wait_proc)
4691 {
4692 if (wait_proc->infd < 0) /* Terminated */
4693 break;
4694 FD_SET (wait_proc->infd, &Available);
4695 check_delay = 0;
4696 check_write = 0;
4697 }
4698 else if (!NILP (wait_for_cell))
4699 {
4700 Available = non_process_wait_mask;
4701 check_delay = 0;
4702 check_write = 0;
4703 }
4704 else
4705 {
4706 if (! read_kbd)
4707 Available = non_keyboard_wait_mask;
4708 else
4709 Available = input_wait_mask;
4710 Writeok = write_mask;
4711 #ifdef SELECT_CANT_DO_WRITE_MASK
4712 check_write = 0;
4713 #else
4714 check_write = 1;
4715 #endif
4716 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4717 }
4718
4719 /* If frame size has changed or the window is newly mapped,
4720 redisplay now, before we start to wait. There is a race
4721 condition here; if a SIGIO arrives between now and the select
4722 and indicates that a frame is trashed, the select may block
4723 displaying a trashed screen. */
4724 if (frame_garbaged && do_display)
4725 {
4726 clear_waiting_for_input ();
4727 redisplay_preserve_echo_area (11);
4728 if (read_kbd < 0)
4729 set_waiting_for_input (&timeout);
4730 }
4731
4732 no_avail = 0;
4733 if (read_kbd && detect_input_pending ())
4734 {
4735 nfds = 0;
4736 no_avail = 1;
4737 }
4738 else
4739 {
4740
4741 #ifdef ADAPTIVE_READ_BUFFERING
4742 /* Set the timeout for adaptive read buffering if any
4743 process has non-zero read_output_skip and non-zero
4744 read_output_delay, and we are not reading output for a
4745 specific wait_channel. It is not executed if
4746 Vprocess_adaptive_read_buffering is nil. */
4747 if (process_output_skip && check_delay > 0)
4748 {
4749 int usecs = EMACS_USECS (timeout);
4750 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4751 usecs = READ_OUTPUT_DELAY_MAX;
4752 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4753 {
4754 proc = chan_process[channel];
4755 if (NILP (proc))
4756 continue;
4757 /* Find minimum non-zero read_output_delay among the
4758 processes with non-zero read_output_skip. */
4759 if (XPROCESS (proc)->read_output_delay > 0)
4760 {
4761 check_delay--;
4762 if (!XPROCESS (proc)->read_output_skip)
4763 continue;
4764 FD_CLR (channel, &Available);
4765 XPROCESS (proc)->read_output_skip = 0;
4766 if (XPROCESS (proc)->read_output_delay < usecs)
4767 usecs = XPROCESS (proc)->read_output_delay;
4768 }
4769 }
4770 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4771 process_output_skip = 0;
4772 }
4773 #endif
4774 #if defined (USE_GTK) || defined (HAVE_GCONF)
4775 nfds = xg_select
4776 #elif defined (HAVE_NS)
4777 nfds = ns_select
4778 #else
4779 nfds = select
4780 #endif
4781 (max (max_process_desc, max_input_desc) + 1,
4782 &Available,
4783 (check_write ? &Writeok : (SELECT_TYPE *)0),
4784 (SELECT_TYPE *)0, &timeout);
4785 }
4786
4787 xerrno = errno;
4788
4789 /* Make C-g and alarm signals set flags again */
4790 clear_waiting_for_input ();
4791
4792 /* If we woke up due to SIGWINCH, actually change size now. */
4793 do_pending_window_change (0);
4794
4795 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4796 /* We wanted the full specified time, so return now. */
4797 break;
4798 if (nfds < 0)
4799 {
4800 if (xerrno == EINTR)
4801 no_avail = 1;
4802 else if (xerrno == EBADF)
4803 {
4804 #ifdef AIX
4805 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4806 the child's closure of the pts gives the parent a SIGHUP, and
4807 the ptc file descriptor is automatically closed,
4808 yielding EBADF here or at select() call above.
4809 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4810 in m/ibmrt-aix.h), and here we just ignore the select error.
4811 Cleanup occurs c/o status_notify after SIGCLD. */
4812 no_avail = 1; /* Cannot depend on values returned */
4813 #else
4814 abort ();
4815 #endif
4816 }
4817 else
4818 error ("select error: %s", emacs_strerror (xerrno));
4819 }
4820
4821 if (no_avail)
4822 {
4823 FD_ZERO (&Available);
4824 check_write = 0;
4825 }
4826
4827 #if 0 /* When polling is used, interrupt_input is 0,
4828 so get_input_pending should read the input.
4829 So this should not be needed. */
4830 /* If we are using polling for input,
4831 and we see input available, make it get read now.
4832 Otherwise it might not actually get read for a second.
4833 And on hpux, since we turn off polling in wait_reading_process_output,
4834 it might never get read at all if we don't spend much time
4835 outside of wait_reading_process_output. */
4836 if (read_kbd && interrupt_input
4837 && keyboard_bit_set (&Available)
4838 && input_polling_used ())
4839 kill (getpid (), SIGALRM);
4840 #endif
4841
4842 /* Check for keyboard input */
4843 /* If there is any, return immediately
4844 to give it higher priority than subprocesses */
4845
4846 if (read_kbd != 0)
4847 {
4848 int old_timers_run = timers_run;
4849 struct buffer *old_buffer = current_buffer;
4850 Lisp_Object old_window = selected_window;
4851 int leave = 0;
4852
4853 if (detect_input_pending_run_timers (do_display))
4854 {
4855 swallow_events (do_display);
4856 if (detect_input_pending_run_timers (do_display))
4857 leave = 1;
4858 }
4859
4860 /* If a timer has run, this might have changed buffers
4861 an alike. Make read_key_sequence aware of that. */
4862 if (timers_run != old_timers_run
4863 && waiting_for_user_input_p == -1
4864 && (old_buffer != current_buffer
4865 || !EQ (old_window, selected_window)))
4866 record_asynch_buffer_change ();
4867
4868 if (leave)
4869 break;
4870 }
4871
4872 /* If there is unread keyboard input, also return. */
4873 if (read_kbd != 0
4874 && requeued_events_pending_p ())
4875 break;
4876
4877 /* If we are not checking for keyboard input now,
4878 do process events (but don't run any timers).
4879 This is so that X events will be processed.
4880 Otherwise they may have to wait until polling takes place.
4881 That would causes delays in pasting selections, for example.
4882
4883 (We used to do this only if wait_for_cell.) */
4884 if (read_kbd == 0 && detect_input_pending ())
4885 {
4886 swallow_events (do_display);
4887 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4888 if (detect_input_pending ())
4889 break;
4890 #endif
4891 }
4892
4893 /* Exit now if the cell we're waiting for became non-nil. */
4894 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4895 break;
4896
4897 #ifdef SIGIO
4898 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4899 go read it. This can happen with X on BSD after logging out.
4900 In that case, there really is no input and no SIGIO,
4901 but select says there is input. */
4902
4903 if (read_kbd && interrupt_input
4904 && keyboard_bit_set (&Available) && ! noninteractive)
4905 kill (getpid (), SIGIO);
4906 #endif
4907
4908 if (! wait_proc)
4909 got_some_input |= nfds > 0;
4910
4911 /* If checking input just got us a size-change event from X,
4912 obey it now if we should. */
4913 if (read_kbd || ! NILP (wait_for_cell))
4914 do_pending_window_change (0);
4915
4916 /* Check for data from a process. */
4917 if (no_avail || nfds == 0)
4918 continue;
4919
4920 for (channel = 0; channel <= max_input_desc; ++channel)
4921 {
4922 struct fd_callback_data *d = &fd_callback_info[channel];
4923 if (FD_ISSET (channel, &Available)
4924 && d->func != 0
4925 && (d->condition & FOR_READ) != 0)
4926 d->func (channel, d->data, 1);
4927 if (FD_ISSET (channel, &write_mask)
4928 && d->func != 0
4929 && (d->condition & FOR_WRITE) != 0)
4930 d->func (channel, d->data, 0);
4931 }
4932
4933 /* Really FIRST_PROC_DESC should be 0 on Unix,
4934 but this is safer in the short run. */
4935 for (channel = 0; channel <= max_process_desc; channel++)
4936 {
4937 if (FD_ISSET (channel, &Available)
4938 && FD_ISSET (channel, &non_keyboard_wait_mask)
4939 && !FD_ISSET (channel, &non_process_wait_mask))
4940 {
4941 int nread;
4942
4943 /* If waiting for this channel, arrange to return as
4944 soon as no more input to be processed. No more
4945 waiting. */
4946 if (wait_channel == channel)
4947 {
4948 wait_channel = -1;
4949 time_limit = -1;
4950 got_some_input = 1;
4951 }
4952 proc = chan_process[channel];
4953 if (NILP (proc))
4954 continue;
4955
4956 /* If this is a server stream socket, accept connection. */
4957 if (EQ (XPROCESS (proc)->status, Qlisten))
4958 {
4959 server_accept_connection (proc, channel);
4960 continue;
4961 }
4962
4963 /* Read data from the process, starting with our
4964 buffered-ahead character if we have one. */
4965
4966 nread = read_process_output (proc, channel);
4967 if (nread > 0)
4968 {
4969 /* Since read_process_output can run a filter,
4970 which can call accept-process-output,
4971 don't try to read from any other processes
4972 before doing the select again. */
4973 FD_ZERO (&Available);
4974
4975 if (do_display)
4976 redisplay_preserve_echo_area (12);
4977 }
4978 #ifdef EWOULDBLOCK
4979 else if (nread == -1 && errno == EWOULDBLOCK)
4980 ;
4981 #endif
4982 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4983 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4984 #ifdef O_NONBLOCK
4985 else if (nread == -1 && errno == EAGAIN)
4986 ;
4987 #else
4988 #ifdef O_NDELAY
4989 else if (nread == -1 && errno == EAGAIN)
4990 ;
4991 /* Note that we cannot distinguish between no input
4992 available now and a closed pipe.
4993 With luck, a closed pipe will be accompanied by
4994 subprocess termination and SIGCHLD. */
4995 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4996 ;
4997 #endif /* O_NDELAY */
4998 #endif /* O_NONBLOCK */
4999 #ifdef HAVE_PTYS
5000 /* On some OSs with ptys, when the process on one end of
5001 a pty exits, the other end gets an error reading with
5002 errno = EIO instead of getting an EOF (0 bytes read).
5003 Therefore, if we get an error reading and errno =
5004 EIO, just continue, because the child process has
5005 exited and should clean itself up soon (e.g. when we
5006 get a SIGCHLD).
5007
5008 However, it has been known to happen that the SIGCHLD
5009 got lost. So raise the signal again just in case.
5010 It can't hurt. */
5011 else if (nread == -1 && errno == EIO)
5012 {
5013 /* Clear the descriptor now, so we only raise the
5014 signal once. Don't do this if `process' is only
5015 a pty. */
5016 if (XPROCESS (proc)->pid != -2)
5017 {
5018 FD_CLR (channel, &input_wait_mask);
5019 FD_CLR (channel, &non_keyboard_wait_mask);
5020
5021 kill (getpid (), SIGCHLD);
5022 }
5023 }
5024 #endif /* HAVE_PTYS */
5025 /* If we can detect process termination, don't consider the process
5026 gone just because its pipe is closed. */
5027 #ifdef SIGCHLD
5028 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5029 ;
5030 #endif
5031 else
5032 {
5033 /* Preserve status of processes already terminated. */
5034 XPROCESS (proc)->tick = ++process_tick;
5035 deactivate_process (proc);
5036 if (XPROCESS (proc)->raw_status_new)
5037 update_status (XPROCESS (proc));
5038 if (EQ (XPROCESS (proc)->status, Qrun))
5039 XPROCESS (proc)->status
5040 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5041 }
5042 }
5043 #ifdef NON_BLOCKING_CONNECT
5044 if (FD_ISSET (channel, &Writeok)
5045 && FD_ISSET (channel, &connect_wait_mask))
5046 {
5047 struct Lisp_Process *p;
5048
5049 FD_CLR (channel, &connect_wait_mask);
5050 FD_CLR (channel, &write_mask);
5051 if (--num_pending_connects < 0)
5052 abort ();
5053
5054 proc = chan_process[channel];
5055 if (NILP (proc))
5056 continue;
5057
5058 p = XPROCESS (proc);
5059
5060 #ifdef GNU_LINUX
5061 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5062 So only use it on systems where it is known to work. */
5063 {
5064 int xlen = sizeof (xerrno);
5065 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5066 xerrno = errno;
5067 }
5068 #else
5069 {
5070 struct sockaddr pname;
5071 int pnamelen = sizeof (pname);
5072
5073 /* If connection failed, getpeername will fail. */
5074 xerrno = 0;
5075 if (getpeername (channel, &pname, &pnamelen) < 0)
5076 {
5077 /* Obtain connect failure code through error slippage. */
5078 char dummy;
5079 xerrno = errno;
5080 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5081 xerrno = errno;
5082 }
5083 }
5084 #endif
5085 if (xerrno)
5086 {
5087 p->tick = ++process_tick;
5088 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5089 deactivate_process (proc);
5090 }
5091 else
5092 {
5093 p->status = Qrun;
5094 /* Execute the sentinel here. If we had relied on
5095 status_notify to do it later, it will read input
5096 from the process before calling the sentinel. */
5097 exec_sentinel (proc, build_string ("open\n"));
5098 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5099 {
5100 FD_SET (p->infd, &input_wait_mask);
5101 FD_SET (p->infd, &non_keyboard_wait_mask);
5102 }
5103 }
5104 }
5105 #endif /* NON_BLOCKING_CONNECT */
5106 } /* end for each file descriptor */
5107 } /* end while exit conditions not met */
5108
5109 unbind_to (count, Qnil);
5110
5111 /* If calling from keyboard input, do not quit
5112 since we want to return C-g as an input character.
5113 Otherwise, do pending quit if requested. */
5114 if (read_kbd >= 0)
5115 {
5116 /* Prevent input_pending from remaining set if we quit. */
5117 clear_input_pending ();
5118 QUIT;
5119 }
5120
5121 return got_some_input;
5122 }
5123 \f
5124 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5125
5126 static Lisp_Object
5127 read_process_output_call (Lisp_Object fun_and_args)
5128 {
5129 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5130 }
5131
5132 static Lisp_Object
5133 read_process_output_error_handler (Lisp_Object error_val)
5134 {
5135 cmd_error_internal (error_val, "error in process filter: ");
5136 Vinhibit_quit = Qt;
5137 update_echo_area ();
5138 Fsleep_for (make_number (2), Qnil);
5139 return Qt;
5140 }
5141
5142 /* Read pending output from the process channel,
5143 starting with our buffered-ahead character if we have one.
5144 Yield number of decoded characters read.
5145
5146 This function reads at most 4096 characters.
5147 If you want to read all available subprocess output,
5148 you must call it repeatedly until it returns zero.
5149
5150 The characters read are decoded according to PROC's coding-system
5151 for decoding. */
5152
5153 static int
5154 read_process_output (Lisp_Object proc, register int channel)
5155 {
5156 register int nbytes;
5157 char *chars;
5158 register Lisp_Object outstream;
5159 register struct Lisp_Process *p = XPROCESS (proc);
5160 register EMACS_INT opoint;
5161 struct coding_system *coding = proc_decode_coding_system[channel];
5162 int carryover = p->decoding_carryover;
5163 int readmax = 4096;
5164 int count = SPECPDL_INDEX ();
5165 Lisp_Object odeactivate;
5166
5167 chars = (char *) alloca (carryover + readmax);
5168 if (carryover)
5169 /* See the comment above. */
5170 memcpy (chars, SDATA (p->decoding_buf), carryover);
5171
5172 #ifdef DATAGRAM_SOCKETS
5173 /* We have a working select, so proc_buffered_char is always -1. */
5174 if (DATAGRAM_CHAN_P (channel))
5175 {
5176 int len = datagram_address[channel].len;
5177 nbytes = recvfrom (channel, chars + carryover, readmax,
5178 0, datagram_address[channel].sa, &len);
5179 }
5180 else
5181 #endif
5182 if (proc_buffered_char[channel] < 0)
5183 {
5184 #ifdef HAVE_GNUTLS
5185 if (XPROCESS (proc)->gnutls_p)
5186 nbytes = emacs_gnutls_read (channel, XPROCESS (proc),
5187 chars + carryover, readmax);
5188 else
5189 #endif
5190 nbytes = emacs_read (channel, chars + carryover, readmax);
5191 #ifdef ADAPTIVE_READ_BUFFERING
5192 if (nbytes > 0 && p->adaptive_read_buffering)
5193 {
5194 int delay = p->read_output_delay;
5195 if (nbytes < 256)
5196 {
5197 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5198 {
5199 if (delay == 0)
5200 process_output_delay_count++;
5201 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5202 }
5203 }
5204 else if (delay > 0 && (nbytes == readmax))
5205 {
5206 delay -= READ_OUTPUT_DELAY_INCREMENT;
5207 if (delay == 0)
5208 process_output_delay_count--;
5209 }
5210 p->read_output_delay = delay;
5211 if (delay)
5212 {
5213 p->read_output_skip = 1;
5214 process_output_skip = 1;
5215 }
5216 }
5217 #endif
5218 }
5219 else
5220 {
5221 chars[carryover] = proc_buffered_char[channel];
5222 proc_buffered_char[channel] = -1;
5223 #ifdef HAVE_GNUTLS
5224 if (XPROCESS (proc)->gnutls_p)
5225 nbytes = emacs_gnutls_read (channel, XPROCESS (proc),
5226 chars + carryover + 1, readmax - 1);
5227 else
5228 #endif
5229 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5230 if (nbytes < 0)
5231 nbytes = 1;
5232 else
5233 nbytes = nbytes + 1;
5234 }
5235
5236 p->decoding_carryover = 0;
5237
5238 /* At this point, NBYTES holds number of bytes just received
5239 (including the one in proc_buffered_char[channel]). */
5240 if (nbytes <= 0)
5241 {
5242 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5243 return nbytes;
5244 coding->mode |= CODING_MODE_LAST_BLOCK;
5245 }
5246
5247 /* Now set NBYTES how many bytes we must decode. */
5248 nbytes += carryover;
5249
5250 odeactivate = Vdeactivate_mark;
5251 /* There's no good reason to let process filters change the current
5252 buffer, and many callers of accept-process-output, sit-for, and
5253 friends don't expect current-buffer to be changed from under them. */
5254 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5255
5256 /* Read and dispose of the process output. */
5257 outstream = p->filter;
5258 if (!NILP (outstream))
5259 {
5260 Lisp_Object obuffer, okeymap;
5261 Lisp_Object text;
5262 int outer_running_asynch_code = running_asynch_code;
5263 int waiting = waiting_for_user_input_p;
5264
5265 /* No need to gcpro these, because all we do with them later
5266 is test them for EQness, and none of them should be a string. */
5267 XSETBUFFER (obuffer, current_buffer);
5268 okeymap = BVAR (current_buffer, keymap);
5269
5270 /* We inhibit quit here instead of just catching it so that
5271 hitting ^G when a filter happens to be running won't screw
5272 it up. */
5273 specbind (Qinhibit_quit, Qt);
5274 specbind (Qlast_nonmenu_event, Qt);
5275
5276 /* In case we get recursively called,
5277 and we already saved the match data nonrecursively,
5278 save the same match data in safely recursive fashion. */
5279 if (outer_running_asynch_code)
5280 {
5281 Lisp_Object tem;
5282 /* Don't clobber the CURRENT match data, either! */
5283 tem = Fmatch_data (Qnil, Qnil, Qnil);
5284 restore_search_regs ();
5285 record_unwind_save_match_data ();
5286 Fset_match_data (tem, Qt);
5287 }
5288
5289 /* For speed, if a search happens within this code,
5290 save the match data in a special nonrecursive fashion. */
5291 running_asynch_code = 1;
5292
5293 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5294 text = coding->dst_object;
5295 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5296 /* A new coding system might be found. */
5297 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5298 {
5299 p->decode_coding_system = Vlast_coding_system_used;
5300
5301 /* Don't call setup_coding_system for
5302 proc_decode_coding_system[channel] here. It is done in
5303 detect_coding called via decode_coding above. */
5304
5305 /* If a coding system for encoding is not yet decided, we set
5306 it as the same as coding-system for decoding.
5307
5308 But, before doing that we must check if
5309 proc_encode_coding_system[p->outfd] surely points to a
5310 valid memory because p->outfd will be changed once EOF is
5311 sent to the process. */
5312 if (NILP (p->encode_coding_system)
5313 && proc_encode_coding_system[p->outfd])
5314 {
5315 p->encode_coding_system
5316 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5317 setup_coding_system (p->encode_coding_system,
5318 proc_encode_coding_system[p->outfd]);
5319 }
5320 }
5321
5322 if (coding->carryover_bytes > 0)
5323 {
5324 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5325 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5326 memcpy (SDATA (p->decoding_buf), coding->carryover,
5327 coding->carryover_bytes);
5328 p->decoding_carryover = coding->carryover_bytes;
5329 }
5330 if (SBYTES (text) > 0)
5331 internal_condition_case_1 (read_process_output_call,
5332 Fcons (outstream,
5333 Fcons (proc, Fcons (text, Qnil))),
5334 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5335 read_process_output_error_handler);
5336
5337 /* If we saved the match data nonrecursively, restore it now. */
5338 restore_search_regs ();
5339 running_asynch_code = outer_running_asynch_code;
5340
5341 /* Restore waiting_for_user_input_p as it was
5342 when we were called, in case the filter clobbered it. */
5343 waiting_for_user_input_p = waiting;
5344
5345 #if 0 /* Call record_asynch_buffer_change unconditionally,
5346 because we might have changed minor modes or other things
5347 that affect key bindings. */
5348 if (! EQ (Fcurrent_buffer (), obuffer)
5349 || ! EQ (current_buffer->keymap, okeymap))
5350 #endif
5351 /* But do it only if the caller is actually going to read events.
5352 Otherwise there's no need to make him wake up, and it could
5353 cause trouble (for example it would make sit_for return). */
5354 if (waiting_for_user_input_p == -1)
5355 record_asynch_buffer_change ();
5356 }
5357
5358 /* If no filter, write into buffer if it isn't dead. */
5359 else if (!NILP (p->buffer) && !NILP (BVAR (XBUFFER (p->buffer), name)))
5360 {
5361 Lisp_Object old_read_only;
5362 EMACS_INT old_begv, old_zv;
5363 EMACS_INT old_begv_byte, old_zv_byte;
5364 EMACS_INT before, before_byte;
5365 EMACS_INT opoint_byte;
5366 Lisp_Object text;
5367 struct buffer *b;
5368
5369 Fset_buffer (p->buffer);
5370 opoint = PT;
5371 opoint_byte = PT_BYTE;
5372 old_read_only = BVAR (current_buffer, read_only);
5373 old_begv = BEGV;
5374 old_zv = ZV;
5375 old_begv_byte = BEGV_BYTE;
5376 old_zv_byte = ZV_BYTE;
5377
5378 BVAR (current_buffer, read_only) = Qnil;
5379
5380 /* Insert new output into buffer
5381 at the current end-of-output marker,
5382 thus preserving logical ordering of input and output. */
5383 if (XMARKER (p->mark)->buffer)
5384 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5385 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5386 ZV_BYTE));
5387 else
5388 SET_PT_BOTH (ZV, ZV_BYTE);
5389 before = PT;
5390 before_byte = PT_BYTE;
5391
5392 /* If the output marker is outside of the visible region, save
5393 the restriction and widen. */
5394 if (! (BEGV <= PT && PT <= ZV))
5395 Fwiden ();
5396
5397 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5398 text = coding->dst_object;
5399 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5400 /* A new coding system might be found. See the comment in the
5401 similar code in the previous `if' block. */
5402 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5403 {
5404 p->decode_coding_system = Vlast_coding_system_used;
5405 if (NILP (p->encode_coding_system)
5406 && proc_encode_coding_system[p->outfd])
5407 {
5408 p->encode_coding_system
5409 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5410 setup_coding_system (p->encode_coding_system,
5411 proc_encode_coding_system[p->outfd]);
5412 }
5413 }
5414 if (coding->carryover_bytes > 0)
5415 {
5416 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5417 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5418 memcpy (SDATA (p->decoding_buf), coding->carryover,
5419 coding->carryover_bytes);
5420 p->decoding_carryover = coding->carryover_bytes;
5421 }
5422 /* Adjust the multibyteness of TEXT to that of the buffer. */
5423 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5424 != ! STRING_MULTIBYTE (text))
5425 text = (STRING_MULTIBYTE (text)
5426 ? Fstring_as_unibyte (text)
5427 : Fstring_to_multibyte (text));
5428 /* Insert before markers in case we are inserting where
5429 the buffer's mark is, and the user's next command is Meta-y. */
5430 insert_from_string_before_markers (text, 0, 0,
5431 SCHARS (text), SBYTES (text), 0);
5432
5433 /* Make sure the process marker's position is valid when the
5434 process buffer is changed in the signal_after_change above.
5435 W3 is known to do that. */
5436 if (BUFFERP (p->buffer)
5437 && (b = XBUFFER (p->buffer), b != current_buffer))
5438 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5439 else
5440 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5441
5442 update_mode_lines++;
5443
5444 /* Make sure opoint and the old restrictions
5445 float ahead of any new text just as point would. */
5446 if (opoint >= before)
5447 {
5448 opoint += PT - before;
5449 opoint_byte += PT_BYTE - before_byte;
5450 }
5451 if (old_begv > before)
5452 {
5453 old_begv += PT - before;
5454 old_begv_byte += PT_BYTE - before_byte;
5455 }
5456 if (old_zv >= before)
5457 {
5458 old_zv += PT - before;
5459 old_zv_byte += PT_BYTE - before_byte;
5460 }
5461
5462 /* If the restriction isn't what it should be, set it. */
5463 if (old_begv != BEGV || old_zv != ZV)
5464 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5465
5466
5467 BVAR (current_buffer, read_only) = old_read_only;
5468 SET_PT_BOTH (opoint, opoint_byte);
5469 }
5470 /* Handling the process output should not deactivate the mark. */
5471 Vdeactivate_mark = odeactivate;
5472
5473 unbind_to (count, Qnil);
5474 return nbytes;
5475 }
5476 \f
5477 /* Sending data to subprocess */
5478
5479 jmp_buf send_process_frame;
5480 Lisp_Object process_sent_to;
5481
5482 static SIGTYPE
5483 send_process_trap (int ignore)
5484 {
5485 SIGNAL_THREAD_CHECK (SIGPIPE);
5486 sigunblock (sigmask (SIGPIPE));
5487 longjmp (send_process_frame, 1);
5488 }
5489
5490 /* Send some data to process PROC.
5491 BUF is the beginning of the data; LEN is the number of characters.
5492 OBJECT is the Lisp object that the data comes from. If OBJECT is
5493 nil or t, it means that the data comes from C string.
5494
5495 If OBJECT is not nil, the data is encoded by PROC's coding-system
5496 for encoding before it is sent.
5497
5498 This function can evaluate Lisp code and can garbage collect. */
5499
5500 static void
5501 send_process (volatile Lisp_Object proc, const char *volatile buf,
5502 volatile EMACS_INT len, volatile Lisp_Object object)
5503 {
5504 /* Use volatile to protect variables from being clobbered by longjmp. */
5505 struct Lisp_Process *p = XPROCESS (proc);
5506 EMACS_INT rv;
5507 struct coding_system *coding;
5508 struct gcpro gcpro1;
5509 SIGTYPE (*volatile old_sigpipe) (int);
5510
5511 GCPRO1 (object);
5512
5513 if (p->raw_status_new)
5514 update_status (p);
5515 if (! EQ (p->status, Qrun))
5516 error ("Process %s not running", SDATA (p->name));
5517 if (p->outfd < 0)
5518 error ("Output file descriptor of %s is closed", SDATA (p->name));
5519
5520 coding = proc_encode_coding_system[p->outfd];
5521 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5522
5523 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5524 || (BUFFERP (object)
5525 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5526 || EQ (object, Qt))
5527 {
5528 p->encode_coding_system
5529 = complement_process_encoding_system (p->encode_coding_system);
5530 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5531 {
5532 /* The coding system for encoding was changed to raw-text
5533 because we sent a unibyte text previously. Now we are
5534 sending a multibyte text, thus we must encode it by the
5535 original coding system specified for the current process.
5536
5537 Another reason we comming here is that the coding system
5538 was just complemented and new one was returned by
5539 complement_process_encoding_system. */
5540 setup_coding_system (p->encode_coding_system, coding);
5541 Vlast_coding_system_used = p->encode_coding_system;
5542 }
5543 coding->src_multibyte = 1;
5544 }
5545 else
5546 {
5547 /* For sending a unibyte text, character code conversion should
5548 not take place but EOL conversion should. So, setup raw-text
5549 or one of the subsidiary if we have not yet done it. */
5550 if (CODING_REQUIRE_ENCODING (coding))
5551 {
5552 if (CODING_REQUIRE_FLUSHING (coding))
5553 {
5554 /* But, before changing the coding, we must flush out data. */
5555 coding->mode |= CODING_MODE_LAST_BLOCK;
5556 send_process (proc, "", 0, Qt);
5557 coding->mode &= CODING_MODE_LAST_BLOCK;
5558 }
5559 setup_coding_system (raw_text_coding_system
5560 (Vlast_coding_system_used),
5561 coding);
5562 coding->src_multibyte = 0;
5563 }
5564 }
5565 coding->dst_multibyte = 0;
5566
5567 if (CODING_REQUIRE_ENCODING (coding))
5568 {
5569 coding->dst_object = Qt;
5570 if (BUFFERP (object))
5571 {
5572 EMACS_INT from_byte, from, to;
5573 EMACS_INT save_pt, save_pt_byte;
5574 struct buffer *cur = current_buffer;
5575
5576 set_buffer_internal (XBUFFER (object));
5577 save_pt = PT, save_pt_byte = PT_BYTE;
5578
5579 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5580 from = BYTE_TO_CHAR (from_byte);
5581 to = BYTE_TO_CHAR (from_byte + len);
5582 TEMP_SET_PT_BOTH (from, from_byte);
5583 encode_coding_object (coding, object, from, from_byte,
5584 to, from_byte + len, Qt);
5585 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5586 set_buffer_internal (cur);
5587 }
5588 else if (STRINGP (object))
5589 {
5590 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5591 SBYTES (object), Qt);
5592 }
5593 else
5594 {
5595 coding->dst_object = make_unibyte_string (buf, len);
5596 coding->produced = len;
5597 }
5598
5599 len = coding->produced;
5600 object = coding->dst_object;
5601 buf = SSDATA (object);
5602 }
5603
5604 if (pty_max_bytes == 0)
5605 {
5606 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5607 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5608 if (pty_max_bytes < 0)
5609 pty_max_bytes = 250;
5610 #else
5611 pty_max_bytes = 250;
5612 #endif
5613 /* Deduct one, to leave space for the eof. */
5614 pty_max_bytes--;
5615 }
5616
5617 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5618 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5619 when returning with longjmp despite being declared volatile. */
5620 if (!setjmp (send_process_frame))
5621 {
5622 process_sent_to = proc;
5623 while (len > 0)
5624 {
5625 EMACS_INT this = len;
5626
5627 /* Send this batch, using one or more write calls. */
5628 while (this > 0)
5629 {
5630 int outfd = p->outfd;
5631 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
5632 #ifdef DATAGRAM_SOCKETS
5633 if (DATAGRAM_CHAN_P (outfd))
5634 {
5635 rv = sendto (outfd, buf, this,
5636 0, datagram_address[outfd].sa,
5637 datagram_address[outfd].len);
5638 if (rv < 0 && errno == EMSGSIZE)
5639 {
5640 signal (SIGPIPE, old_sigpipe);
5641 report_file_error ("sending datagram",
5642 Fcons (proc, Qnil));
5643 }
5644 }
5645 else
5646 #endif
5647 {
5648 #ifdef HAVE_GNUTLS
5649 if (XPROCESS (proc)->gnutls_p)
5650 rv = emacs_gnutls_write (outfd,
5651 XPROCESS (proc),
5652 buf, this);
5653 else
5654 #endif
5655 rv = emacs_write (outfd, buf, this);
5656 #ifdef ADAPTIVE_READ_BUFFERING
5657 if (p->read_output_delay > 0
5658 && p->adaptive_read_buffering == 1)
5659 {
5660 p->read_output_delay = 0;
5661 process_output_delay_count--;
5662 p->read_output_skip = 0;
5663 }
5664 #endif
5665 }
5666 signal (SIGPIPE, old_sigpipe);
5667
5668 if (rv < 0)
5669 {
5670 if (0
5671 #ifdef EWOULDBLOCK
5672 || errno == EWOULDBLOCK
5673 #endif
5674 #ifdef EAGAIN
5675 || errno == EAGAIN
5676 #endif
5677 )
5678 /* Buffer is full. Wait, accepting input;
5679 that may allow the program
5680 to finish doing output and read more. */
5681 {
5682 int offset = 0;
5683
5684 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5685 /* A gross hack to work around a bug in FreeBSD.
5686 In the following sequence, read(2) returns
5687 bogus data:
5688
5689 write(2) 1022 bytes
5690 write(2) 954 bytes, get EAGAIN
5691 read(2) 1024 bytes in process_read_output
5692 read(2) 11 bytes in process_read_output
5693
5694 That is, read(2) returns more bytes than have
5695 ever been written successfully. The 1033 bytes
5696 read are the 1022 bytes written successfully
5697 after processing (for example with CRs added if
5698 the terminal is set up that way which it is
5699 here). The same bytes will be seen again in a
5700 later read(2), without the CRs. */
5701
5702 if (errno == EAGAIN)
5703 {
5704 int flags = FWRITE;
5705 ioctl (p->outfd, TIOCFLUSH, &flags);
5706 }
5707 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5708
5709 /* Running filters might relocate buffers or strings.
5710 Arrange to relocate BUF. */
5711 if (BUFFERP (object))
5712 offset = BUF_PTR_BYTE_POS (XBUFFER (object),
5713 (unsigned char *) buf);
5714 else if (STRINGP (object))
5715 offset = buf - SSDATA (object);
5716
5717 #ifdef EMACS_HAS_USECS
5718 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5719 #else
5720 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5721 #endif
5722
5723 if (BUFFERP (object))
5724 buf = (char *) BUF_BYTE_ADDRESS (XBUFFER (object),
5725 offset);
5726 else if (STRINGP (object))
5727 buf = offset + SSDATA (object);
5728
5729 rv = 0;
5730 }
5731 else
5732 /* This is a real error. */
5733 report_file_error ("writing to process", Fcons (proc, Qnil));
5734 }
5735 buf += rv;
5736 len -= rv;
5737 this -= rv;
5738 }
5739 }
5740 }
5741 else
5742 {
5743 signal (SIGPIPE, old_sigpipe);
5744 proc = process_sent_to;
5745 p = XPROCESS (proc);
5746 p->raw_status_new = 0;
5747 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5748 p->tick = ++process_tick;
5749 deactivate_process (proc);
5750 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5751 }
5752
5753 UNGCPRO;
5754 }
5755
5756 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5757 3, 3, 0,
5758 doc: /* Send current contents of region as input to PROCESS.
5759 PROCESS may be a process, a buffer, the name of a process or buffer, or
5760 nil, indicating the current buffer's process.
5761 Called from program, takes three arguments, PROCESS, START and END.
5762 If the region is more than 500 characters long,
5763 it is sent in several bunches. This may happen even for shorter regions.
5764 Output from processes can arrive in between bunches. */)
5765 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5766 {
5767 Lisp_Object proc;
5768 EMACS_INT start1, end1;
5769
5770 proc = get_process (process);
5771 validate_region (&start, &end);
5772
5773 if (XINT (start) < GPT && XINT (end) > GPT)
5774 move_gap (XINT (start));
5775
5776 start1 = CHAR_TO_BYTE (XINT (start));
5777 end1 = CHAR_TO_BYTE (XINT (end));
5778 send_process (proc, (char *) BYTE_POS_ADDR (start1), end1 - start1,
5779 Fcurrent_buffer ());
5780
5781 return Qnil;
5782 }
5783
5784 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5785 2, 2, 0,
5786 doc: /* Send PROCESS the contents of STRING as input.
5787 PROCESS may be a process, a buffer, the name of a process or buffer, or
5788 nil, indicating the current buffer's process.
5789 If STRING is more than 500 characters long,
5790 it is sent in several bunches. This may happen even for shorter strings.
5791 Output from processes can arrive in between bunches. */)
5792 (Lisp_Object process, Lisp_Object string)
5793 {
5794 Lisp_Object proc;
5795 CHECK_STRING (string);
5796 proc = get_process (process);
5797 send_process (proc, SSDATA (string),
5798 SBYTES (string), string);
5799 return Qnil;
5800 }
5801 \f
5802 /* Return the foreground process group for the tty/pty that
5803 the process P uses. */
5804 static int
5805 emacs_get_tty_pgrp (struct Lisp_Process *p)
5806 {
5807 int gid = -1;
5808
5809 #ifdef TIOCGPGRP
5810 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5811 {
5812 int fd;
5813 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5814 master side. Try the slave side. */
5815 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5816
5817 if (fd != -1)
5818 {
5819 ioctl (fd, TIOCGPGRP, &gid);
5820 emacs_close (fd);
5821 }
5822 }
5823 #endif /* defined (TIOCGPGRP ) */
5824
5825 return gid;
5826 }
5827
5828 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5829 Sprocess_running_child_p, 0, 1, 0,
5830 doc: /* Return t if PROCESS has given the terminal to a child.
5831 If the operating system does not make it possible to find out,
5832 return t unconditionally. */)
5833 (Lisp_Object process)
5834 {
5835 /* Initialize in case ioctl doesn't exist or gives an error,
5836 in a way that will cause returning t. */
5837 int gid;
5838 Lisp_Object proc;
5839 struct Lisp_Process *p;
5840
5841 proc = get_process (process);
5842 p = XPROCESS (proc);
5843
5844 if (!EQ (p->type, Qreal))
5845 error ("Process %s is not a subprocess",
5846 SDATA (p->name));
5847 if (p->infd < 0)
5848 error ("Process %s is not active",
5849 SDATA (p->name));
5850
5851 gid = emacs_get_tty_pgrp (p);
5852
5853 if (gid == p->pid)
5854 return Qnil;
5855 return Qt;
5856 }
5857 \f
5858 /* send a signal number SIGNO to PROCESS.
5859 If CURRENT_GROUP is t, that means send to the process group
5860 that currently owns the terminal being used to communicate with PROCESS.
5861 This is used for various commands in shell mode.
5862 If CURRENT_GROUP is lambda, that means send to the process group
5863 that currently owns the terminal, but only if it is NOT the shell itself.
5864
5865 If NOMSG is zero, insert signal-announcements into process's buffers
5866 right away.
5867
5868 If we can, we try to signal PROCESS by sending control characters
5869 down the pty. This allows us to signal inferiors who have changed
5870 their uid, for which killpg would return an EPERM error. */
5871
5872 static void
5873 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5874 int nomsg)
5875 {
5876 Lisp_Object proc;
5877 register struct Lisp_Process *p;
5878 int gid;
5879 int no_pgrp = 0;
5880
5881 proc = get_process (process);
5882 p = XPROCESS (proc);
5883
5884 if (!EQ (p->type, Qreal))
5885 error ("Process %s is not a subprocess",
5886 SDATA (p->name));
5887 if (p->infd < 0)
5888 error ("Process %s is not active",
5889 SDATA (p->name));
5890
5891 if (!p->pty_flag)
5892 current_group = Qnil;
5893
5894 /* If we are using pgrps, get a pgrp number and make it negative. */
5895 if (NILP (current_group))
5896 /* Send the signal to the shell's process group. */
5897 gid = p->pid;
5898 else
5899 {
5900 #ifdef SIGNALS_VIA_CHARACTERS
5901 /* If possible, send signals to the entire pgrp
5902 by sending an input character to it. */
5903
5904 struct termios t;
5905 cc_t *sig_char = NULL;
5906
5907 tcgetattr (p->infd, &t);
5908
5909 switch (signo)
5910 {
5911 case SIGINT:
5912 sig_char = &t.c_cc[VINTR];
5913 break;
5914
5915 case SIGQUIT:
5916 sig_char = &t.c_cc[VQUIT];
5917 break;
5918
5919 case SIGTSTP:
5920 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5921 sig_char = &t.c_cc[VSWTCH];
5922 #else
5923 sig_char = &t.c_cc[VSUSP];
5924 #endif
5925 break;
5926 }
5927
5928 if (sig_char && *sig_char != CDISABLE)
5929 {
5930 send_process (proc, sig_char, 1, Qnil);
5931 return;
5932 }
5933 /* If we can't send the signal with a character,
5934 fall through and send it another way. */
5935
5936 /* The code above may fall through if it can't
5937 handle the signal. */
5938 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5939
5940 #ifdef TIOCGPGRP
5941 /* Get the current pgrp using the tty itself, if we have that.
5942 Otherwise, use the pty to get the pgrp.
5943 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5944 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5945 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5946 His patch indicates that if TIOCGPGRP returns an error, then
5947 we should just assume that p->pid is also the process group id. */
5948
5949 gid = emacs_get_tty_pgrp (p);
5950
5951 if (gid == -1)
5952 /* If we can't get the information, assume
5953 the shell owns the tty. */
5954 gid = p->pid;
5955
5956 /* It is not clear whether anything really can set GID to -1.
5957 Perhaps on some system one of those ioctls can or could do so.
5958 Or perhaps this is vestigial. */
5959 if (gid == -1)
5960 no_pgrp = 1;
5961 #else /* ! defined (TIOCGPGRP ) */
5962 /* Can't select pgrps on this system, so we know that
5963 the child itself heads the pgrp. */
5964 gid = p->pid;
5965 #endif /* ! defined (TIOCGPGRP ) */
5966
5967 /* If current_group is lambda, and the shell owns the terminal,
5968 don't send any signal. */
5969 if (EQ (current_group, Qlambda) && gid == p->pid)
5970 return;
5971 }
5972
5973 switch (signo)
5974 {
5975 #ifdef SIGCONT
5976 case SIGCONT:
5977 p->raw_status_new = 0;
5978 p->status = Qrun;
5979 p->tick = ++process_tick;
5980 if (!nomsg)
5981 {
5982 status_notify (NULL);
5983 redisplay_preserve_echo_area (13);
5984 }
5985 break;
5986 #endif /* ! defined (SIGCONT) */
5987 case SIGINT:
5988 case SIGQUIT:
5989 case SIGKILL:
5990 flush_pending_output (p->infd);
5991 break;
5992 }
5993
5994 /* If we don't have process groups, send the signal to the immediate
5995 subprocess. That isn't really right, but it's better than any
5996 obvious alternative. */
5997 if (no_pgrp)
5998 {
5999 kill (p->pid, signo);
6000 return;
6001 }
6002
6003 /* gid may be a pid, or minus a pgrp's number */
6004 #ifdef TIOCSIGSEND
6005 if (!NILP (current_group))
6006 {
6007 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6008 EMACS_KILLPG (gid, signo);
6009 }
6010 else
6011 {
6012 gid = - p->pid;
6013 kill (gid, signo);
6014 }
6015 #else /* ! defined (TIOCSIGSEND) */
6016 EMACS_KILLPG (gid, signo);
6017 #endif /* ! defined (TIOCSIGSEND) */
6018 }
6019
6020 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6021 doc: /* Interrupt process PROCESS.
6022 PROCESS may be a process, a buffer, or the name of a process or buffer.
6023 No arg or nil means current buffer's process.
6024 Second arg CURRENT-GROUP non-nil means send signal to
6025 the current process-group of the process's controlling terminal
6026 rather than to the process's own process group.
6027 If the process is a shell, this means interrupt current subjob
6028 rather than the shell.
6029
6030 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6031 don't send the signal. */)
6032 (Lisp_Object process, Lisp_Object current_group)
6033 {
6034 process_send_signal (process, SIGINT, current_group, 0);
6035 return process;
6036 }
6037
6038 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6039 doc: /* Kill process PROCESS. May be process or name of one.
6040 See function `interrupt-process' for more details on usage. */)
6041 (Lisp_Object process, Lisp_Object current_group)
6042 {
6043 process_send_signal (process, SIGKILL, current_group, 0);
6044 return process;
6045 }
6046
6047 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6048 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6049 See function `interrupt-process' for more details on usage. */)
6050 (Lisp_Object process, Lisp_Object current_group)
6051 {
6052 process_send_signal (process, SIGQUIT, current_group, 0);
6053 return process;
6054 }
6055
6056 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6057 doc: /* Stop process PROCESS. May be process or name of one.
6058 See function `interrupt-process' for more details on usage.
6059 If PROCESS is a network or serial process, inhibit handling of incoming
6060 traffic. */)
6061 (Lisp_Object process, Lisp_Object current_group)
6062 {
6063 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6064 {
6065 struct Lisp_Process *p;
6066
6067 p = XPROCESS (process);
6068 if (NILP (p->command)
6069 && p->infd >= 0)
6070 {
6071 FD_CLR (p->infd, &input_wait_mask);
6072 FD_CLR (p->infd, &non_keyboard_wait_mask);
6073 }
6074 p->command = Qt;
6075 return process;
6076 }
6077 #ifndef SIGTSTP
6078 error ("No SIGTSTP support");
6079 #else
6080 process_send_signal (process, SIGTSTP, current_group, 0);
6081 #endif
6082 return process;
6083 }
6084
6085 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6086 doc: /* Continue process PROCESS. May be process or name of one.
6087 See function `interrupt-process' for more details on usage.
6088 If PROCESS is a network or serial process, resume handling of incoming
6089 traffic. */)
6090 (Lisp_Object process, Lisp_Object current_group)
6091 {
6092 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6093 {
6094 struct Lisp_Process *p;
6095
6096 p = XPROCESS (process);
6097 if (EQ (p->command, Qt)
6098 && p->infd >= 0
6099 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6100 {
6101 FD_SET (p->infd, &input_wait_mask);
6102 FD_SET (p->infd, &non_keyboard_wait_mask);
6103 #ifdef WINDOWSNT
6104 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6105 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6106 #else /* not WINDOWSNT */
6107 tcflush (p->infd, TCIFLUSH);
6108 #endif /* not WINDOWSNT */
6109 }
6110 p->command = Qnil;
6111 return process;
6112 }
6113 #ifdef SIGCONT
6114 process_send_signal (process, SIGCONT, current_group, 0);
6115 #else
6116 error ("No SIGCONT support");
6117 #endif
6118 return process;
6119 }
6120
6121 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6122 2, 2, "sProcess (name or number): \nnSignal code: ",
6123 doc: /* Send PROCESS the signal with code SIGCODE.
6124 PROCESS may also be a number specifying the process id of the
6125 process to signal; in this case, the process need not be a child of
6126 this Emacs.
6127 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6128 (Lisp_Object process, Lisp_Object sigcode)
6129 {
6130 pid_t pid;
6131
6132 if (INTEGERP (process))
6133 {
6134 pid = XINT (process);
6135 goto got_it;
6136 }
6137
6138 if (FLOATP (process))
6139 {
6140 pid = (pid_t) XFLOAT_DATA (process);
6141 goto got_it;
6142 }
6143
6144 if (STRINGP (process))
6145 {
6146 Lisp_Object tem;
6147 if (tem = Fget_process (process), NILP (tem))
6148 {
6149 pid = XINT (Fstring_to_number (process, make_number (10)));
6150 if (pid > 0)
6151 goto got_it;
6152 }
6153 process = tem;
6154 }
6155 else
6156 process = get_process (process);
6157
6158 if (NILP (process))
6159 return process;
6160
6161 CHECK_PROCESS (process);
6162 pid = XPROCESS (process)->pid;
6163 if (pid <= 0)
6164 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6165
6166 got_it:
6167
6168 #define parse_signal(NAME, VALUE) \
6169 else if (!xstrcasecmp (name, NAME)) \
6170 XSETINT (sigcode, VALUE)
6171
6172 if (INTEGERP (sigcode))
6173 ;
6174 else
6175 {
6176 char *name;
6177
6178 CHECK_SYMBOL (sigcode);
6179 name = SSDATA (SYMBOL_NAME (sigcode));
6180
6181 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6182 name += 3;
6183
6184 if (0)
6185 ;
6186 #ifdef SIGUSR1
6187 parse_signal ("usr1", SIGUSR1);
6188 #endif
6189 #ifdef SIGUSR2
6190 parse_signal ("usr2", SIGUSR2);
6191 #endif
6192 #ifdef SIGTERM
6193 parse_signal ("term", SIGTERM);
6194 #endif
6195 #ifdef SIGHUP
6196 parse_signal ("hup", SIGHUP);
6197 #endif
6198 #ifdef SIGINT
6199 parse_signal ("int", SIGINT);
6200 #endif
6201 #ifdef SIGQUIT
6202 parse_signal ("quit", SIGQUIT);
6203 #endif
6204 #ifdef SIGILL
6205 parse_signal ("ill", SIGILL);
6206 #endif
6207 #ifdef SIGABRT
6208 parse_signal ("abrt", SIGABRT);
6209 #endif
6210 #ifdef SIGEMT
6211 parse_signal ("emt", SIGEMT);
6212 #endif
6213 #ifdef SIGKILL
6214 parse_signal ("kill", SIGKILL);
6215 #endif
6216 #ifdef SIGFPE
6217 parse_signal ("fpe", SIGFPE);
6218 #endif
6219 #ifdef SIGBUS
6220 parse_signal ("bus", SIGBUS);
6221 #endif
6222 #ifdef SIGSEGV
6223 parse_signal ("segv", SIGSEGV);
6224 #endif
6225 #ifdef SIGSYS
6226 parse_signal ("sys", SIGSYS);
6227 #endif
6228 #ifdef SIGPIPE
6229 parse_signal ("pipe", SIGPIPE);
6230 #endif
6231 #ifdef SIGALRM
6232 parse_signal ("alrm", SIGALRM);
6233 #endif
6234 #ifdef SIGURG
6235 parse_signal ("urg", SIGURG);
6236 #endif
6237 #ifdef SIGSTOP
6238 parse_signal ("stop", SIGSTOP);
6239 #endif
6240 #ifdef SIGTSTP
6241 parse_signal ("tstp", SIGTSTP);
6242 #endif
6243 #ifdef SIGCONT
6244 parse_signal ("cont", SIGCONT);
6245 #endif
6246 #ifdef SIGCHLD
6247 parse_signal ("chld", SIGCHLD);
6248 #endif
6249 #ifdef SIGTTIN
6250 parse_signal ("ttin", SIGTTIN);
6251 #endif
6252 #ifdef SIGTTOU
6253 parse_signal ("ttou", SIGTTOU);
6254 #endif
6255 #ifdef SIGIO
6256 parse_signal ("io", SIGIO);
6257 #endif
6258 #ifdef SIGXCPU
6259 parse_signal ("xcpu", SIGXCPU);
6260 #endif
6261 #ifdef SIGXFSZ
6262 parse_signal ("xfsz", SIGXFSZ);
6263 #endif
6264 #ifdef SIGVTALRM
6265 parse_signal ("vtalrm", SIGVTALRM);
6266 #endif
6267 #ifdef SIGPROF
6268 parse_signal ("prof", SIGPROF);
6269 #endif
6270 #ifdef SIGWINCH
6271 parse_signal ("winch", SIGWINCH);
6272 #endif
6273 #ifdef SIGINFO
6274 parse_signal ("info", SIGINFO);
6275 #endif
6276 else
6277 error ("Undefined signal name %s", name);
6278 }
6279
6280 #undef parse_signal
6281
6282 return make_number (kill (pid, XINT (sigcode)));
6283 }
6284
6285 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6286 doc: /* Make PROCESS see end-of-file in its input.
6287 EOF comes after any text already sent to it.
6288 PROCESS may be a process, a buffer, the name of a process or buffer, or
6289 nil, indicating the current buffer's process.
6290 If PROCESS is a network connection, or is a process communicating
6291 through a pipe (as opposed to a pty), then you cannot send any more
6292 text to PROCESS after you call this function.
6293 If PROCESS is a serial process, wait until all output written to the
6294 process has been transmitted to the serial port. */)
6295 (Lisp_Object process)
6296 {
6297 Lisp_Object proc;
6298 struct coding_system *coding;
6299
6300 if (DATAGRAM_CONN_P (process))
6301 return process;
6302
6303 proc = get_process (process);
6304 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6305
6306 /* Make sure the process is really alive. */
6307 if (XPROCESS (proc)->raw_status_new)
6308 update_status (XPROCESS (proc));
6309 if (! EQ (XPROCESS (proc)->status, Qrun))
6310 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6311
6312 if (CODING_REQUIRE_FLUSHING (coding))
6313 {
6314 coding->mode |= CODING_MODE_LAST_BLOCK;
6315 send_process (proc, "", 0, Qnil);
6316 }
6317
6318 if (XPROCESS (proc)->pty_flag)
6319 send_process (proc, "\004", 1, Qnil);
6320 else if (EQ (XPROCESS (proc)->type, Qserial))
6321 {
6322 #ifndef WINDOWSNT
6323 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6324 error ("tcdrain() failed: %s", emacs_strerror (errno));
6325 #endif /* not WINDOWSNT */
6326 /* Do nothing on Windows because writes are blocking. */
6327 }
6328 else
6329 {
6330 int old_outfd, new_outfd;
6331
6332 #ifdef HAVE_SHUTDOWN
6333 /* If this is a network connection, or socketpair is used
6334 for communication with the subprocess, call shutdown to cause EOF.
6335 (In some old system, shutdown to socketpair doesn't work.
6336 Then we just can't win.) */
6337 if (EQ (XPROCESS (proc)->type, Qnetwork)
6338 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6339 shutdown (XPROCESS (proc)->outfd, 1);
6340 /* In case of socketpair, outfd == infd, so don't close it. */
6341 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6342 emacs_close (XPROCESS (proc)->outfd);
6343 #else /* not HAVE_SHUTDOWN */
6344 emacs_close (XPROCESS (proc)->outfd);
6345 #endif /* not HAVE_SHUTDOWN */
6346 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6347 if (new_outfd < 0)
6348 abort ();
6349 old_outfd = XPROCESS (proc)->outfd;
6350
6351 if (!proc_encode_coding_system[new_outfd])
6352 proc_encode_coding_system[new_outfd]
6353 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6354 memcpy (proc_encode_coding_system[new_outfd],
6355 proc_encode_coding_system[old_outfd],
6356 sizeof (struct coding_system));
6357 memset (proc_encode_coding_system[old_outfd], 0,
6358 sizeof (struct coding_system));
6359
6360 XPROCESS (proc)->outfd = new_outfd;
6361 }
6362 return process;
6363 }
6364 \f
6365 /* On receipt of a signal that a child status has changed, loop asking
6366 about children with changed statuses until the system says there
6367 are no more.
6368
6369 All we do is change the status; we do not run sentinels or print
6370 notifications. That is saved for the next time keyboard input is
6371 done, in order to avoid timing errors.
6372
6373 ** WARNING: this can be called during garbage collection.
6374 Therefore, it must not be fooled by the presence of mark bits in
6375 Lisp objects.
6376
6377 ** USG WARNING: Although it is not obvious from the documentation
6378 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6379 signal() before executing at least one wait(), otherwise the
6380 handler will be called again, resulting in an infinite loop. The
6381 relevant portion of the documentation reads "SIGCLD signals will be
6382 queued and the signal-catching function will be continually
6383 reentered until the queue is empty". Invoking signal() causes the
6384 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6385 Inc.
6386
6387 ** Malloc WARNING: This should never call malloc either directly or
6388 indirectly; if it does, that is a bug */
6389
6390 #ifdef SIGCHLD
6391 static SIGTYPE
6392 sigchld_handler (int signo)
6393 {
6394 int old_errno = errno;
6395 Lisp_Object proc;
6396 struct Lisp_Process *p;
6397
6398 SIGNAL_THREAD_CHECK (signo);
6399
6400 while (1)
6401 {
6402 pid_t pid;
6403 int w;
6404 Lisp_Object tail;
6405
6406 #ifdef WNOHANG
6407 #ifndef WUNTRACED
6408 #define WUNTRACED 0
6409 #endif /* no WUNTRACED */
6410 /* Keep trying to get a status until we get a definitive result. */
6411 do
6412 {
6413 errno = 0;
6414 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6415 }
6416 while (pid < 0 && errno == EINTR);
6417
6418 if (pid <= 0)
6419 {
6420 /* PID == 0 means no processes found, PID == -1 means a real
6421 failure. We have done all our job, so return. */
6422
6423 errno = old_errno;
6424 return;
6425 }
6426 #else
6427 pid = wait (&w);
6428 #endif /* no WNOHANG */
6429
6430 /* Find the process that signaled us, and record its status. */
6431
6432 /* The process can have been deleted by Fdelete_process. */
6433 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6434 {
6435 Lisp_Object xpid = XCAR (tail);
6436 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6437 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6438 {
6439 XSETCAR (tail, Qnil);
6440 goto sigchld_end_of_loop;
6441 }
6442 }
6443
6444 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6445 p = 0;
6446 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6447 {
6448 proc = XCDR (XCAR (tail));
6449 p = XPROCESS (proc);
6450 if (EQ (p->type, Qreal) && p->pid == pid)
6451 break;
6452 p = 0;
6453 }
6454
6455 /* Look for an asynchronous process whose pid hasn't been filled
6456 in yet. */
6457 if (p == 0)
6458 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6459 {
6460 proc = XCDR (XCAR (tail));
6461 p = XPROCESS (proc);
6462 if (p->pid == -1)
6463 break;
6464 p = 0;
6465 }
6466
6467 /* Change the status of the process that was found. */
6468 if (p != 0)
6469 {
6470 int clear_desc_flag = 0;
6471
6472 p->tick = ++process_tick;
6473 p->raw_status = w;
6474 p->raw_status_new = 1;
6475
6476 /* If process has terminated, stop waiting for its output. */
6477 if ((WIFSIGNALED (w) || WIFEXITED (w))
6478 && p->infd >= 0)
6479 clear_desc_flag = 1;
6480
6481 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6482 if (clear_desc_flag)
6483 {
6484 FD_CLR (p->infd, &input_wait_mask);
6485 FD_CLR (p->infd, &non_keyboard_wait_mask);
6486 }
6487
6488 /* Tell wait_reading_process_output that it needs to wake up and
6489 look around. */
6490 if (input_available_clear_time)
6491 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6492 }
6493
6494 /* There was no asynchronous process found for that pid: we have
6495 a synchronous process. */
6496 else
6497 {
6498 synch_process_alive = 0;
6499
6500 /* Report the status of the synchronous process. */
6501 if (WIFEXITED (w))
6502 synch_process_retcode = WRETCODE (w);
6503 else if (WIFSIGNALED (w))
6504 synch_process_termsig = WTERMSIG (w);
6505
6506 /* Tell wait_reading_process_output that it needs to wake up and
6507 look around. */
6508 if (input_available_clear_time)
6509 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6510 }
6511
6512 sigchld_end_of_loop:
6513 ;
6514
6515 /* On some systems, we must return right away.
6516 If any more processes want to signal us, we will
6517 get another signal.
6518 Otherwise (on systems that have WNOHANG), loop around
6519 to use up all the processes that have something to tell us. */
6520 #if (defined WINDOWSNT \
6521 || (defined USG && !defined GNU_LINUX \
6522 && !(defined HPUX && defined WNOHANG)))
6523 errno = old_errno;
6524 return;
6525 #endif /* USG, but not HPUX with WNOHANG */
6526 }
6527 }
6528 #endif /* SIGCHLD */
6529 \f
6530
6531 static Lisp_Object
6532 exec_sentinel_unwind (Lisp_Object data)
6533 {
6534 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6535 return Qnil;
6536 }
6537
6538 static Lisp_Object
6539 exec_sentinel_error_handler (Lisp_Object error_val)
6540 {
6541 cmd_error_internal (error_val, "error in process sentinel: ");
6542 Vinhibit_quit = Qt;
6543 update_echo_area ();
6544 Fsleep_for (make_number (2), Qnil);
6545 return Qt;
6546 }
6547
6548 static void
6549 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6550 {
6551 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6552 register struct Lisp_Process *p = XPROCESS (proc);
6553 int count = SPECPDL_INDEX ();
6554 int outer_running_asynch_code = running_asynch_code;
6555 int waiting = waiting_for_user_input_p;
6556
6557 if (inhibit_sentinels)
6558 return;
6559
6560 /* No need to gcpro these, because all we do with them later
6561 is test them for EQness, and none of them should be a string. */
6562 odeactivate = Vdeactivate_mark;
6563 XSETBUFFER (obuffer, current_buffer);
6564 okeymap = BVAR (current_buffer, keymap);
6565
6566 /* There's no good reason to let sentinels change the current
6567 buffer, and many callers of accept-process-output, sit-for, and
6568 friends don't expect current-buffer to be changed from under them. */
6569 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6570
6571 sentinel = p->sentinel;
6572 if (NILP (sentinel))
6573 return;
6574
6575 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6576 assure that it gets restored no matter how the sentinel exits. */
6577 p->sentinel = Qnil;
6578 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6579 /* Inhibit quit so that random quits don't screw up a running filter. */
6580 specbind (Qinhibit_quit, Qt);
6581 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6582
6583 /* In case we get recursively called,
6584 and we already saved the match data nonrecursively,
6585 save the same match data in safely recursive fashion. */
6586 if (outer_running_asynch_code)
6587 {
6588 Lisp_Object tem;
6589 tem = Fmatch_data (Qnil, Qnil, Qnil);
6590 restore_search_regs ();
6591 record_unwind_save_match_data ();
6592 Fset_match_data (tem, Qt);
6593 }
6594
6595 /* For speed, if a search happens within this code,
6596 save the match data in a special nonrecursive fashion. */
6597 running_asynch_code = 1;
6598
6599 internal_condition_case_1 (read_process_output_call,
6600 Fcons (sentinel,
6601 Fcons (proc, Fcons (reason, Qnil))),
6602 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6603 exec_sentinel_error_handler);
6604
6605 /* If we saved the match data nonrecursively, restore it now. */
6606 restore_search_regs ();
6607 running_asynch_code = outer_running_asynch_code;
6608
6609 Vdeactivate_mark = odeactivate;
6610
6611 /* Restore waiting_for_user_input_p as it was
6612 when we were called, in case the filter clobbered it. */
6613 waiting_for_user_input_p = waiting;
6614
6615 #if 0
6616 if (! EQ (Fcurrent_buffer (), obuffer)
6617 || ! EQ (current_buffer->keymap, okeymap))
6618 #endif
6619 /* But do it only if the caller is actually going to read events.
6620 Otherwise there's no need to make him wake up, and it could
6621 cause trouble (for example it would make sit_for return). */
6622 if (waiting_for_user_input_p == -1)
6623 record_asynch_buffer_change ();
6624
6625 unbind_to (count, Qnil);
6626 }
6627
6628 /* Report all recent events of a change in process status
6629 (either run the sentinel or output a message).
6630 This is usually done while Emacs is waiting for keyboard input
6631 but can be done at other times. */
6632
6633 static void
6634 status_notify (struct Lisp_Process *deleting_process)
6635 {
6636 register Lisp_Object proc, buffer;
6637 Lisp_Object tail, msg;
6638 struct gcpro gcpro1, gcpro2;
6639
6640 tail = Qnil;
6641 msg = Qnil;
6642 /* We need to gcpro tail; if read_process_output calls a filter
6643 which deletes a process and removes the cons to which tail points
6644 from Vprocess_alist, and then causes a GC, tail is an unprotected
6645 reference. */
6646 GCPRO2 (tail, msg);
6647
6648 /* Set this now, so that if new processes are created by sentinels
6649 that we run, we get called again to handle their status changes. */
6650 update_tick = process_tick;
6651
6652 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6653 {
6654 Lisp_Object symbol;
6655 register struct Lisp_Process *p;
6656
6657 proc = Fcdr (XCAR (tail));
6658 p = XPROCESS (proc);
6659
6660 if (p->tick != p->update_tick)
6661 {
6662 p->update_tick = p->tick;
6663
6664 /* If process is still active, read any output that remains. */
6665 while (! EQ (p->filter, Qt)
6666 && ! EQ (p->status, Qconnect)
6667 && ! EQ (p->status, Qlisten)
6668 /* Network or serial process not stopped: */
6669 && ! EQ (p->command, Qt)
6670 && p->infd >= 0
6671 && p != deleting_process
6672 && read_process_output (proc, p->infd) > 0);
6673
6674 buffer = p->buffer;
6675
6676 /* Get the text to use for the message. */
6677 if (p->raw_status_new)
6678 update_status (p);
6679 msg = status_message (p);
6680
6681 /* If process is terminated, deactivate it or delete it. */
6682 symbol = p->status;
6683 if (CONSP (p->status))
6684 symbol = XCAR (p->status);
6685
6686 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6687 || EQ (symbol, Qclosed))
6688 {
6689 if (delete_exited_processes)
6690 remove_process (proc);
6691 else
6692 deactivate_process (proc);
6693 }
6694
6695 /* The actions above may have further incremented p->tick.
6696 So set p->update_tick again
6697 so that an error in the sentinel will not cause
6698 this code to be run again. */
6699 p->update_tick = p->tick;
6700 /* Now output the message suitably. */
6701 if (!NILP (p->sentinel))
6702 exec_sentinel (proc, msg);
6703 /* Don't bother with a message in the buffer
6704 when a process becomes runnable. */
6705 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6706 {
6707 Lisp_Object tem;
6708 struct buffer *old = current_buffer;
6709 EMACS_INT opoint, opoint_byte;
6710 EMACS_INT before, before_byte;
6711
6712 /* Avoid error if buffer is deleted
6713 (probably that's why the process is dead, too) */
6714 if (NILP (BVAR (XBUFFER (buffer), name)))
6715 continue;
6716 Fset_buffer (buffer);
6717
6718 opoint = PT;
6719 opoint_byte = PT_BYTE;
6720 /* Insert new output into buffer
6721 at the current end-of-output marker,
6722 thus preserving logical ordering of input and output. */
6723 if (XMARKER (p->mark)->buffer)
6724 Fgoto_char (p->mark);
6725 else
6726 SET_PT_BOTH (ZV, ZV_BYTE);
6727
6728 before = PT;
6729 before_byte = PT_BYTE;
6730
6731 tem = BVAR (current_buffer, read_only);
6732 BVAR (current_buffer, read_only) = Qnil;
6733 insert_string ("\nProcess ");
6734 Finsert (1, &p->name);
6735 insert_string (" ");
6736 Finsert (1, &msg);
6737 BVAR (current_buffer, read_only) = tem;
6738 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6739
6740 if (opoint >= before)
6741 SET_PT_BOTH (opoint + (PT - before),
6742 opoint_byte + (PT_BYTE - before_byte));
6743 else
6744 SET_PT_BOTH (opoint, opoint_byte);
6745
6746 set_buffer_internal (old);
6747 }
6748 }
6749 } /* end for */
6750
6751 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6752 UNGCPRO;
6753 }
6754
6755 \f
6756 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6757 Sset_process_coding_system, 1, 3, 0,
6758 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6759 DECODING will be used to decode subprocess output and ENCODING to
6760 encode subprocess input. */)
6761 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6762 {
6763 register struct Lisp_Process *p;
6764
6765 CHECK_PROCESS (process);
6766 p = XPROCESS (process);
6767 if (p->infd < 0)
6768 error ("Input file descriptor of %s closed", SDATA (p->name));
6769 if (p->outfd < 0)
6770 error ("Output file descriptor of %s closed", SDATA (p->name));
6771 Fcheck_coding_system (decoding);
6772 Fcheck_coding_system (encoding);
6773 encoding = coding_inherit_eol_type (encoding, Qnil);
6774 p->decode_coding_system = decoding;
6775 p->encode_coding_system = encoding;
6776 setup_process_coding_systems (process);
6777
6778 return Qnil;
6779 }
6780
6781 DEFUN ("process-coding-system",
6782 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6783 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6784 (register Lisp_Object process)
6785 {
6786 CHECK_PROCESS (process);
6787 return Fcons (XPROCESS (process)->decode_coding_system,
6788 XPROCESS (process)->encode_coding_system);
6789 }
6790
6791 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6792 Sset_process_filter_multibyte, 2, 2, 0,
6793 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6794 If FLAG is non-nil, the filter is given multibyte strings.
6795 If FLAG is nil, the filter is given unibyte strings. In this case,
6796 all character code conversion except for end-of-line conversion is
6797 suppressed. */)
6798 (Lisp_Object process, Lisp_Object flag)
6799 {
6800 register struct Lisp_Process *p;
6801
6802 CHECK_PROCESS (process);
6803 p = XPROCESS (process);
6804 if (NILP (flag))
6805 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6806 setup_process_coding_systems (process);
6807
6808 return Qnil;
6809 }
6810
6811 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6812 Sprocess_filter_multibyte_p, 1, 1, 0,
6813 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6814 (Lisp_Object process)
6815 {
6816 register struct Lisp_Process *p;
6817 struct coding_system *coding;
6818
6819 CHECK_PROCESS (process);
6820 p = XPROCESS (process);
6821 coding = proc_decode_coding_system[p->infd];
6822 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6823 }
6824
6825
6826 \f
6827
6828 void
6829 add_gpm_wait_descriptor (int desc)
6830 {
6831 add_keyboard_wait_descriptor (desc);
6832 }
6833
6834 void
6835 delete_gpm_wait_descriptor (int desc)
6836 {
6837 delete_keyboard_wait_descriptor (desc);
6838 }
6839
6840 /* Return nonzero if *MASK has a bit set
6841 that corresponds to one of the keyboard input descriptors. */
6842
6843 static int
6844 keyboard_bit_set (fd_set *mask)
6845 {
6846 int fd;
6847
6848 for (fd = 0; fd <= max_input_desc; fd++)
6849 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6850 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6851 return 1;
6852
6853 return 0;
6854 }
6855
6856 #else /* not subprocesses */
6857
6858 /* Defined on msdos.c. */
6859 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6860 EMACS_TIME *);
6861
6862 /* Implementation of wait_reading_process_output, assuming that there
6863 are no subprocesses. Used only by the MS-DOS build.
6864
6865 Wait for timeout to elapse and/or keyboard input to be available.
6866
6867 time_limit is:
6868 timeout in seconds, or
6869 zero for no limit, or
6870 -1 means gobble data immediately available but don't wait for any.
6871
6872 read_kbd is a Lisp_Object:
6873 0 to ignore keyboard input, or
6874 1 to return when input is available, or
6875 -1 means caller will actually read the input, so don't throw to
6876 the quit handler.
6877
6878 see full version for other parameters. We know that wait_proc will
6879 always be NULL, since `subprocesses' isn't defined.
6880
6881 do_display != 0 means redisplay should be done to show subprocess
6882 output that arrives.
6883
6884 Return true if we received input from any process. */
6885
6886 int
6887 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
6888 int do_display,
6889 Lisp_Object wait_for_cell,
6890 struct Lisp_Process *wait_proc, int just_wait_proc)
6891 {
6892 register int nfds;
6893 EMACS_TIME end_time, timeout;
6894 SELECT_TYPE waitchannels;
6895 int xerrno;
6896
6897 /* What does time_limit really mean? */
6898 if (time_limit || microsecs)
6899 {
6900 EMACS_GET_TIME (end_time);
6901 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6902 EMACS_ADD_TIME (end_time, end_time, timeout);
6903 }
6904
6905 /* Turn off periodic alarms (in case they are in use)
6906 and then turn off any other atimers,
6907 because the select emulator uses alarms. */
6908 stop_polling ();
6909 turn_on_atimers (0);
6910
6911 while (1)
6912 {
6913 int timeout_reduced_for_timers = 0;
6914
6915 /* If calling from keyboard input, do not quit
6916 since we want to return C-g as an input character.
6917 Otherwise, do pending quit if requested. */
6918 if (read_kbd >= 0)
6919 QUIT;
6920
6921 /* Exit now if the cell we're waiting for became non-nil. */
6922 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6923 break;
6924
6925 /* Compute time from now till when time limit is up */
6926 /* Exit if already run out */
6927 if (time_limit == -1)
6928 {
6929 /* -1 specified for timeout means
6930 gobble output available now
6931 but don't wait at all. */
6932
6933 EMACS_SET_SECS_USECS (timeout, 0, 0);
6934 }
6935 else if (time_limit || microsecs)
6936 {
6937 EMACS_GET_TIME (timeout);
6938 EMACS_SUB_TIME (timeout, end_time, timeout);
6939 if (EMACS_TIME_NEG_P (timeout))
6940 break;
6941 }
6942 else
6943 {
6944 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6945 }
6946
6947 /* If our caller will not immediately handle keyboard events,
6948 run timer events directly.
6949 (Callers that will immediately read keyboard events
6950 call timer_delay on their own.) */
6951 if (NILP (wait_for_cell))
6952 {
6953 EMACS_TIME timer_delay;
6954
6955 do
6956 {
6957 int old_timers_run = timers_run;
6958 timer_delay = timer_check (1);
6959 if (timers_run != old_timers_run && do_display)
6960 /* We must retry, since a timer may have requeued itself
6961 and that could alter the time delay. */
6962 redisplay_preserve_echo_area (14);
6963 else
6964 break;
6965 }
6966 while (!detect_input_pending ());
6967
6968 /* If there is unread keyboard input, also return. */
6969 if (read_kbd != 0
6970 && requeued_events_pending_p ())
6971 break;
6972
6973 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
6974 {
6975 EMACS_TIME difference;
6976 EMACS_SUB_TIME (difference, timer_delay, timeout);
6977 if (EMACS_TIME_NEG_P (difference))
6978 {
6979 timeout = timer_delay;
6980 timeout_reduced_for_timers = 1;
6981 }
6982 }
6983 }
6984
6985 /* Cause C-g and alarm signals to take immediate action,
6986 and cause input available signals to zero out timeout. */
6987 if (read_kbd < 0)
6988 set_waiting_for_input (&timeout);
6989
6990 /* Wait till there is something to do. */
6991
6992 if (! read_kbd && NILP (wait_for_cell))
6993 FD_ZERO (&waitchannels);
6994 else
6995 FD_SET (0, &waitchannels);
6996
6997 /* If a frame has been newly mapped and needs updating,
6998 reprocess its display stuff. */
6999 if (frame_garbaged && do_display)
7000 {
7001 clear_waiting_for_input ();
7002 redisplay_preserve_echo_area (15);
7003 if (read_kbd < 0)
7004 set_waiting_for_input (&timeout);
7005 }
7006
7007 if (read_kbd && detect_input_pending ())
7008 {
7009 nfds = 0;
7010 FD_ZERO (&waitchannels);
7011 }
7012 else
7013 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7014 &timeout);
7015
7016 xerrno = errno;
7017
7018 /* Make C-g and alarm signals set flags again */
7019 clear_waiting_for_input ();
7020
7021 /* If we woke up due to SIGWINCH, actually change size now. */
7022 do_pending_window_change (0);
7023
7024 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7025 /* We waited the full specified time, so return now. */
7026 break;
7027
7028 if (nfds == -1)
7029 {
7030 /* If the system call was interrupted, then go around the
7031 loop again. */
7032 if (xerrno == EINTR)
7033 FD_ZERO (&waitchannels);
7034 else
7035 error ("select error: %s", emacs_strerror (xerrno));
7036 }
7037
7038 /* Check for keyboard input */
7039
7040 if (read_kbd
7041 && detect_input_pending_run_timers (do_display))
7042 {
7043 swallow_events (do_display);
7044 if (detect_input_pending_run_timers (do_display))
7045 break;
7046 }
7047
7048 /* If there is unread keyboard input, also return. */
7049 if (read_kbd
7050 && requeued_events_pending_p ())
7051 break;
7052
7053 /* If wait_for_cell. check for keyboard input
7054 but don't run any timers.
7055 ??? (It seems wrong to me to check for keyboard
7056 input at all when wait_for_cell, but the code
7057 has been this way since July 1994.
7058 Try changing this after version 19.31.) */
7059 if (! NILP (wait_for_cell)
7060 && detect_input_pending ())
7061 {
7062 swallow_events (do_display);
7063 if (detect_input_pending ())
7064 break;
7065 }
7066
7067 /* Exit now if the cell we're waiting for became non-nil. */
7068 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7069 break;
7070 }
7071
7072 start_polling ();
7073
7074 return 0;
7075 }
7076
7077 #endif /* not subprocesses */
7078
7079 /* The following functions are needed even if async subprocesses are
7080 not supported. Some of them are no-op stubs in that case. */
7081
7082 /* Add DESC to the set of keyboard input descriptors. */
7083
7084 void
7085 add_keyboard_wait_descriptor (int desc)
7086 {
7087 #ifdef subprocesses /* actually means "not MSDOS" */
7088 FD_SET (desc, &input_wait_mask);
7089 FD_SET (desc, &non_process_wait_mask);
7090 if (desc > max_input_desc)
7091 max_input_desc = desc;
7092 #endif
7093 }
7094
7095 /* From now on, do not expect DESC to give keyboard input. */
7096
7097 void
7098 delete_keyboard_wait_descriptor (int desc)
7099 {
7100 #ifdef subprocesses
7101 int fd;
7102 int lim = max_input_desc;
7103
7104 FD_CLR (desc, &input_wait_mask);
7105 FD_CLR (desc, &non_process_wait_mask);
7106
7107 if (desc == max_input_desc)
7108 for (fd = 0; fd < lim; fd++)
7109 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
7110 max_input_desc = fd;
7111 #endif
7112 }
7113
7114 /* Setup coding systems of PROCESS. */
7115
7116 void
7117 setup_process_coding_systems (Lisp_Object process)
7118 {
7119 #ifdef subprocesses
7120 struct Lisp_Process *p = XPROCESS (process);
7121 int inch = p->infd;
7122 int outch = p->outfd;
7123 Lisp_Object coding_system;
7124
7125 if (inch < 0 || outch < 0)
7126 return;
7127
7128 if (!proc_decode_coding_system[inch])
7129 proc_decode_coding_system[inch]
7130 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7131 coding_system = p->decode_coding_system;
7132 if (! NILP (p->filter))
7133 ;
7134 else if (BUFFERP (p->buffer))
7135 {
7136 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7137 coding_system = raw_text_coding_system (coding_system);
7138 }
7139 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7140
7141 if (!proc_encode_coding_system[outch])
7142 proc_encode_coding_system[outch]
7143 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7144 setup_coding_system (p->encode_coding_system,
7145 proc_encode_coding_system[outch]);
7146 #endif
7147 }
7148
7149 /* Close all descriptors currently in use for communication
7150 with subprocess. This is used in a newly-forked subprocess
7151 to get rid of irrelevant descriptors. */
7152
7153 void
7154 close_process_descs (void)
7155 {
7156 #ifndef DOS_NT
7157 int i;
7158 for (i = 0; i < MAXDESC; i++)
7159 {
7160 Lisp_Object process;
7161 process = chan_process[i];
7162 if (!NILP (process))
7163 {
7164 int in = XPROCESS (process)->infd;
7165 int out = XPROCESS (process)->outfd;
7166 if (in >= 0)
7167 emacs_close (in);
7168 if (out >= 0 && in != out)
7169 emacs_close (out);
7170 }
7171 }
7172 #endif
7173 }
7174
7175 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7176 doc: /* Return the (or a) process associated with BUFFER.
7177 BUFFER may be a buffer or the name of one. */)
7178 (register Lisp_Object buffer)
7179 {
7180 #ifdef subprocesses
7181 register Lisp_Object buf, tail, proc;
7182
7183 if (NILP (buffer)) return Qnil;
7184 buf = Fget_buffer (buffer);
7185 if (NILP (buf)) return Qnil;
7186
7187 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7188 {
7189 proc = Fcdr (XCAR (tail));
7190 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7191 return proc;
7192 }
7193 #endif /* subprocesses */
7194 return Qnil;
7195 }
7196
7197 DEFUN ("process-inherit-coding-system-flag",
7198 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7199 1, 1, 0,
7200 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7201 If this flag is t, `buffer-file-coding-system' of the buffer
7202 associated with PROCESS will inherit the coding system used to decode
7203 the process output. */)
7204 (register Lisp_Object process)
7205 {
7206 #ifdef subprocesses
7207 CHECK_PROCESS (process);
7208 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7209 #else
7210 /* Ignore the argument and return the value of
7211 inherit-process-coding-system. */
7212 return inherit_process_coding_system ? Qt : Qnil;
7213 #endif
7214 }
7215
7216 /* Kill all processes associated with `buffer'.
7217 If `buffer' is nil, kill all processes */
7218
7219 void
7220 kill_buffer_processes (Lisp_Object buffer)
7221 {
7222 #ifdef subprocesses
7223 Lisp_Object tail, proc;
7224
7225 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7226 {
7227 proc = XCDR (XCAR (tail));
7228 if (PROCESSP (proc)
7229 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7230 {
7231 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7232 Fdelete_process (proc);
7233 else if (XPROCESS (proc)->infd >= 0)
7234 process_send_signal (proc, SIGHUP, Qnil, 1);
7235 }
7236 }
7237 #else /* subprocesses */
7238 /* Since we have no subprocesses, this does nothing. */
7239 #endif /* subprocesses */
7240 }
7241
7242 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
7243 0, 0, 0,
7244 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7245 This is intended for use by asynchronous process output filters and sentinels. */)
7246 (void)
7247 {
7248 #ifdef subprocesses
7249 return (waiting_for_user_input_p ? Qt : Qnil);
7250 #else
7251 return Qnil;
7252 #endif
7253 }
7254
7255 /* Stop reading input from keyboard sources. */
7256
7257 void
7258 hold_keyboard_input (void)
7259 {
7260 kbd_is_on_hold = 1;
7261 }
7262
7263 /* Resume reading input from keyboard sources. */
7264
7265 void
7266 unhold_keyboard_input (void)
7267 {
7268 kbd_is_on_hold = 0;
7269 }
7270
7271 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7272
7273 int
7274 kbd_on_hold_p (void)
7275 {
7276 return kbd_is_on_hold;
7277 }
7278
7279 \f
7280 /* Enumeration of and access to system processes a-la ps(1). */
7281
7282 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7283 0, 0, 0,
7284 doc: /* Return a list of numerical process IDs of all running processes.
7285 If this functionality is unsupported, return nil.
7286
7287 See `process-attributes' for getting attributes of a process given its ID. */)
7288 (void)
7289 {
7290 return list_system_processes ();
7291 }
7292
7293 DEFUN ("process-attributes", Fprocess_attributes,
7294 Sprocess_attributes, 1, 1, 0,
7295 doc: /* Return attributes of the process given by its PID, a number.
7296
7297 Value is an alist where each element is a cons cell of the form
7298
7299 \(KEY . VALUE)
7300
7301 If this functionality is unsupported, the value is nil.
7302
7303 See `list-system-processes' for getting a list of all process IDs.
7304
7305 The KEYs of the attributes that this function may return are listed
7306 below, together with the type of the associated VALUE (in parentheses).
7307 Not all platforms support all of these attributes; unsupported
7308 attributes will not appear in the returned alist.
7309 Unless explicitly indicated otherwise, numbers can have either
7310 integer or floating point values.
7311
7312 euid -- Effective user User ID of the process (number)
7313 user -- User name corresponding to euid (string)
7314 egid -- Effective user Group ID of the process (number)
7315 group -- Group name corresponding to egid (string)
7316 comm -- Command name (executable name only) (string)
7317 state -- Process state code, such as "S", "R", or "T" (string)
7318 ppid -- Parent process ID (number)
7319 pgrp -- Process group ID (number)
7320 sess -- Session ID, i.e. process ID of session leader (number)
7321 ttname -- Controlling tty name (string)
7322 tpgid -- ID of foreground process group on the process's tty (number)
7323 minflt -- number of minor page faults (number)
7324 majflt -- number of major page faults (number)
7325 cminflt -- cumulative number of minor page faults (number)
7326 cmajflt -- cumulative number of major page faults (number)
7327 utime -- user time used by the process, in the (HIGH LOW USEC) format
7328 stime -- system time used by the process, in the (HIGH LOW USEC) format
7329 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7330 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7331 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7332 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7333 pri -- priority of the process (number)
7334 nice -- nice value of the process (number)
7335 thcount -- process thread count (number)
7336 start -- time the process started, in the (HIGH LOW USEC) format
7337 vsize -- virtual memory size of the process in KB's (number)
7338 rss -- resident set size of the process in KB's (number)
7339 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7340 pcpu -- percents of CPU time used by the process (floating-point number)
7341 pmem -- percents of total physical memory used by process's resident set
7342 (floating-point number)
7343 args -- command line which invoked the process (string). */)
7344 ( Lisp_Object pid)
7345 {
7346 return system_process_attributes (pid);
7347 }
7348
7349 \f
7350 void
7351 init_process (void)
7352 {
7353 #ifdef subprocesses
7354 register int i;
7355
7356 inhibit_sentinels = 0;
7357
7358 #ifdef SIGCHLD
7359 #ifndef CANNOT_DUMP
7360 if (! noninteractive || initialized)
7361 #endif
7362 signal (SIGCHLD, sigchld_handler);
7363 #endif
7364
7365 FD_ZERO (&input_wait_mask);
7366 FD_ZERO (&non_keyboard_wait_mask);
7367 FD_ZERO (&non_process_wait_mask);
7368 FD_ZERO (&write_mask);
7369 max_process_desc = 0;
7370 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7371
7372 #ifdef NON_BLOCKING_CONNECT
7373 FD_ZERO (&connect_wait_mask);
7374 num_pending_connects = 0;
7375 #endif
7376
7377 #ifdef ADAPTIVE_READ_BUFFERING
7378 process_output_delay_count = 0;
7379 process_output_skip = 0;
7380 #endif
7381
7382 /* Don't do this, it caused infinite select loops. The display
7383 method should call add_keyboard_wait_descriptor on stdin if it
7384 needs that. */
7385 #if 0
7386 FD_SET (0, &input_wait_mask);
7387 #endif
7388
7389 Vprocess_alist = Qnil;
7390 #ifdef SIGCHLD
7391 deleted_pid_list = Qnil;
7392 #endif
7393 for (i = 0; i < MAXDESC; i++)
7394 {
7395 chan_process[i] = Qnil;
7396 proc_buffered_char[i] = -1;
7397 }
7398 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7399 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7400 #ifdef DATAGRAM_SOCKETS
7401 memset (datagram_address, 0, sizeof datagram_address);
7402 #endif
7403
7404 {
7405 Lisp_Object subfeatures = Qnil;
7406 const struct socket_options *sopt;
7407
7408 #define ADD_SUBFEATURE(key, val) \
7409 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7410
7411 #ifdef NON_BLOCKING_CONNECT
7412 ADD_SUBFEATURE (QCnowait, Qt);
7413 #endif
7414 #ifdef DATAGRAM_SOCKETS
7415 ADD_SUBFEATURE (QCtype, Qdatagram);
7416 #endif
7417 #ifdef HAVE_SEQPACKET
7418 ADD_SUBFEATURE (QCtype, Qseqpacket);
7419 #endif
7420 #ifdef HAVE_LOCAL_SOCKETS
7421 ADD_SUBFEATURE (QCfamily, Qlocal);
7422 #endif
7423 ADD_SUBFEATURE (QCfamily, Qipv4);
7424 #ifdef AF_INET6
7425 ADD_SUBFEATURE (QCfamily, Qipv6);
7426 #endif
7427 #ifdef HAVE_GETSOCKNAME
7428 ADD_SUBFEATURE (QCservice, Qt);
7429 #endif
7430 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7431 ADD_SUBFEATURE (QCserver, Qt);
7432 #endif
7433
7434 for (sopt = socket_options; sopt->name; sopt++)
7435 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7436
7437 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7438 }
7439
7440 #if defined (DARWIN_OS)
7441 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7442 processes. As such, we only change the default value. */
7443 if (initialized)
7444 {
7445 const char *release = get_operating_system_release ();
7446 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7447 && release[1] == '.')) {
7448 Vprocess_connection_type = Qnil;
7449 }
7450 }
7451 #endif
7452 #endif /* subprocesses */
7453 kbd_is_on_hold = 0;
7454 }
7455
7456 void
7457 syms_of_process (void)
7458 {
7459 #ifdef subprocesses
7460
7461 Qprocessp = intern_c_string ("processp");
7462 staticpro (&Qprocessp);
7463 Qrun = intern_c_string ("run");
7464 staticpro (&Qrun);
7465 Qstop = intern_c_string ("stop");
7466 staticpro (&Qstop);
7467 Qsignal = intern_c_string ("signal");
7468 staticpro (&Qsignal);
7469
7470 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7471 here again.
7472
7473 Qexit = intern_c_string ("exit");
7474 staticpro (&Qexit); */
7475
7476 Qopen = intern_c_string ("open");
7477 staticpro (&Qopen);
7478 Qclosed = intern_c_string ("closed");
7479 staticpro (&Qclosed);
7480 Qconnect = intern_c_string ("connect");
7481 staticpro (&Qconnect);
7482 Qfailed = intern_c_string ("failed");
7483 staticpro (&Qfailed);
7484 Qlisten = intern_c_string ("listen");
7485 staticpro (&Qlisten);
7486 Qlocal = intern_c_string ("local");
7487 staticpro (&Qlocal);
7488 Qipv4 = intern_c_string ("ipv4");
7489 staticpro (&Qipv4);
7490 #ifdef AF_INET6
7491 Qipv6 = intern_c_string ("ipv6");
7492 staticpro (&Qipv6);
7493 #endif
7494 Qdatagram = intern_c_string ("datagram");
7495 staticpro (&Qdatagram);
7496 Qseqpacket = intern_c_string ("seqpacket");
7497 staticpro (&Qseqpacket);
7498
7499 QCport = intern_c_string (":port");
7500 staticpro (&QCport);
7501 QCspeed = intern_c_string (":speed");
7502 staticpro (&QCspeed);
7503 QCprocess = intern_c_string (":process");
7504 staticpro (&QCprocess);
7505
7506 QCbytesize = intern_c_string (":bytesize");
7507 staticpro (&QCbytesize);
7508 QCstopbits = intern_c_string (":stopbits");
7509 staticpro (&QCstopbits);
7510 QCparity = intern_c_string (":parity");
7511 staticpro (&QCparity);
7512 Qodd = intern_c_string ("odd");
7513 staticpro (&Qodd);
7514 Qeven = intern_c_string ("even");
7515 staticpro (&Qeven);
7516 QCflowcontrol = intern_c_string (":flowcontrol");
7517 staticpro (&QCflowcontrol);
7518 Qhw = intern_c_string ("hw");
7519 staticpro (&Qhw);
7520 Qsw = intern_c_string ("sw");
7521 staticpro (&Qsw);
7522 QCsummary = intern_c_string (":summary");
7523 staticpro (&QCsummary);
7524
7525 Qreal = intern_c_string ("real");
7526 staticpro (&Qreal);
7527 Qnetwork = intern_c_string ("network");
7528 staticpro (&Qnetwork);
7529 Qserial = intern_c_string ("serial");
7530 staticpro (&Qserial);
7531 QCbuffer = intern_c_string (":buffer");
7532 staticpro (&QCbuffer);
7533 QChost = intern_c_string (":host");
7534 staticpro (&QChost);
7535 QCservice = intern_c_string (":service");
7536 staticpro (&QCservice);
7537 QClocal = intern_c_string (":local");
7538 staticpro (&QClocal);
7539 QCremote = intern_c_string (":remote");
7540 staticpro (&QCremote);
7541 QCcoding = intern_c_string (":coding");
7542 staticpro (&QCcoding);
7543 QCserver = intern_c_string (":server");
7544 staticpro (&QCserver);
7545 QCnowait = intern_c_string (":nowait");
7546 staticpro (&QCnowait);
7547 QCsentinel = intern_c_string (":sentinel");
7548 staticpro (&QCsentinel);
7549 QClog = intern_c_string (":log");
7550 staticpro (&QClog);
7551 QCnoquery = intern_c_string (":noquery");
7552 staticpro (&QCnoquery);
7553 QCstop = intern_c_string (":stop");
7554 staticpro (&QCstop);
7555 QCoptions = intern_c_string (":options");
7556 staticpro (&QCoptions);
7557 QCplist = intern_c_string (":plist");
7558 staticpro (&QCplist);
7559
7560 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7561 staticpro (&Qlast_nonmenu_event);
7562
7563 staticpro (&Vprocess_alist);
7564 #ifdef SIGCHLD
7565 staticpro (&deleted_pid_list);
7566 #endif
7567
7568 #endif /* subprocesses */
7569
7570 QCname = intern_c_string (":name");
7571 staticpro (&QCname);
7572 QCtype = intern_c_string (":type");
7573 staticpro (&QCtype);
7574
7575 Qeuid = intern_c_string ("euid");
7576 staticpro (&Qeuid);
7577 Qegid = intern_c_string ("egid");
7578 staticpro (&Qegid);
7579 Quser = intern_c_string ("user");
7580 staticpro (&Quser);
7581 Qgroup = intern_c_string ("group");
7582 staticpro (&Qgroup);
7583 Qcomm = intern_c_string ("comm");
7584 staticpro (&Qcomm);
7585 Qstate = intern_c_string ("state");
7586 staticpro (&Qstate);
7587 Qppid = intern_c_string ("ppid");
7588 staticpro (&Qppid);
7589 Qpgrp = intern_c_string ("pgrp");
7590 staticpro (&Qpgrp);
7591 Qsess = intern_c_string ("sess");
7592 staticpro (&Qsess);
7593 Qttname = intern_c_string ("ttname");
7594 staticpro (&Qttname);
7595 Qtpgid = intern_c_string ("tpgid");
7596 staticpro (&Qtpgid);
7597 Qminflt = intern_c_string ("minflt");
7598 staticpro (&Qminflt);
7599 Qmajflt = intern_c_string ("majflt");
7600 staticpro (&Qmajflt);
7601 Qcminflt = intern_c_string ("cminflt");
7602 staticpro (&Qcminflt);
7603 Qcmajflt = intern_c_string ("cmajflt");
7604 staticpro (&Qcmajflt);
7605 Qutime = intern_c_string ("utime");
7606 staticpro (&Qutime);
7607 Qstime = intern_c_string ("stime");
7608 staticpro (&Qstime);
7609 Qtime = intern_c_string ("time");
7610 staticpro (&Qtime);
7611 Qcutime = intern_c_string ("cutime");
7612 staticpro (&Qcutime);
7613 Qcstime = intern_c_string ("cstime");
7614 staticpro (&Qcstime);
7615 Qctime = intern_c_string ("ctime");
7616 staticpro (&Qctime);
7617 Qpri = intern_c_string ("pri");
7618 staticpro (&Qpri);
7619 Qnice = intern_c_string ("nice");
7620 staticpro (&Qnice);
7621 Qthcount = intern_c_string ("thcount");
7622 staticpro (&Qthcount);
7623 Qstart = intern_c_string ("start");
7624 staticpro (&Qstart);
7625 Qvsize = intern_c_string ("vsize");
7626 staticpro (&Qvsize);
7627 Qrss = intern_c_string ("rss");
7628 staticpro (&Qrss);
7629 Qetime = intern_c_string ("etime");
7630 staticpro (&Qetime);
7631 Qpcpu = intern_c_string ("pcpu");
7632 staticpro (&Qpcpu);
7633 Qpmem = intern_c_string ("pmem");
7634 staticpro (&Qpmem);
7635 Qargs = intern_c_string ("args");
7636 staticpro (&Qargs);
7637
7638 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7639 doc: /* *Non-nil means delete processes immediately when they exit.
7640 A value of nil means don't delete them until `list-processes' is run. */);
7641
7642 delete_exited_processes = 1;
7643
7644 #ifdef subprocesses
7645 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7646 doc: /* Control type of device used to communicate with subprocesses.
7647 Values are nil to use a pipe, or t or `pty' to use a pty.
7648 The value has no effect if the system has no ptys or if all ptys are busy:
7649 then a pipe is used in any case.
7650 The value takes effect when `start-process' is called. */);
7651 Vprocess_connection_type = Qt;
7652
7653 #ifdef ADAPTIVE_READ_BUFFERING
7654 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7655 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7656 On some systems, when Emacs reads the output from a subprocess, the output data
7657 is read in very small blocks, potentially resulting in very poor performance.
7658 This behavior can be remedied to some extent by setting this variable to a
7659 non-nil value, as it will automatically delay reading from such processes, to
7660 allow them to produce more output before Emacs tries to read it.
7661 If the value is t, the delay is reset after each write to the process; any other
7662 non-nil value means that the delay is not reset on write.
7663 The variable takes effect when `start-process' is called. */);
7664 Vprocess_adaptive_read_buffering = Qt;
7665 #endif
7666
7667 defsubr (&Sprocessp);
7668 defsubr (&Sget_process);
7669 defsubr (&Sdelete_process);
7670 defsubr (&Sprocess_status);
7671 defsubr (&Sprocess_exit_status);
7672 defsubr (&Sprocess_id);
7673 defsubr (&Sprocess_name);
7674 defsubr (&Sprocess_tty_name);
7675 defsubr (&Sprocess_command);
7676 defsubr (&Sset_process_buffer);
7677 defsubr (&Sprocess_buffer);
7678 defsubr (&Sprocess_mark);
7679 defsubr (&Sset_process_filter);
7680 defsubr (&Sprocess_filter);
7681 defsubr (&Sset_process_sentinel);
7682 defsubr (&Sprocess_sentinel);
7683 defsubr (&Sset_process_window_size);
7684 defsubr (&Sset_process_inherit_coding_system_flag);
7685 defsubr (&Sset_process_query_on_exit_flag);
7686 defsubr (&Sprocess_query_on_exit_flag);
7687 defsubr (&Sprocess_contact);
7688 defsubr (&Sprocess_plist);
7689 defsubr (&Sset_process_plist);
7690 defsubr (&Slist_processes);
7691 defsubr (&Sprocess_list);
7692 defsubr (&Sstart_process);
7693 defsubr (&Sserial_process_configure);
7694 defsubr (&Smake_serial_process);
7695 defsubr (&Sset_network_process_option);
7696 defsubr (&Smake_network_process);
7697 defsubr (&Sformat_network_address);
7698 #if defined(HAVE_NET_IF_H)
7699 #ifdef SIOCGIFCONF
7700 defsubr (&Snetwork_interface_list);
7701 #endif
7702 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7703 defsubr (&Snetwork_interface_info);
7704 #endif
7705 #endif /* defined(HAVE_NET_IF_H) */
7706 #ifdef DATAGRAM_SOCKETS
7707 defsubr (&Sprocess_datagram_address);
7708 defsubr (&Sset_process_datagram_address);
7709 #endif
7710 defsubr (&Saccept_process_output);
7711 defsubr (&Sprocess_send_region);
7712 defsubr (&Sprocess_send_string);
7713 defsubr (&Sinterrupt_process);
7714 defsubr (&Skill_process);
7715 defsubr (&Squit_process);
7716 defsubr (&Sstop_process);
7717 defsubr (&Scontinue_process);
7718 defsubr (&Sprocess_running_child_p);
7719 defsubr (&Sprocess_send_eof);
7720 defsubr (&Ssignal_process);
7721 defsubr (&Swaiting_for_user_input_p);
7722 defsubr (&Sprocess_type);
7723 defsubr (&Sset_process_coding_system);
7724 defsubr (&Sprocess_coding_system);
7725 defsubr (&Sset_process_filter_multibyte);
7726 defsubr (&Sprocess_filter_multibyte_p);
7727
7728 #endif /* subprocesses */
7729
7730 defsubr (&Sget_buffer_process);
7731 defsubr (&Sprocess_inherit_coding_system_flag);
7732 defsubr (&Slist_system_processes);
7733 defsubr (&Sprocess_attributes);
7734 }