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